31
\$\begingroup\$

I've been posting relatively hard challenges recently, so here goes an easy one.

Task

Given an array \$A\$ and a number \$n\$, calculate the sum of all numbers of \$A\$ multiplied by \$n\$, except the last one. All numbers (the elements of \$A\$ and the value of \$n\$) are positive integers, and \$A\$ is non-empty. Shortest code in bytes wins.

I have a 3-byte J solution. Can you find it (or beat it in a different language)?

Test cases

A           N   Ans   Explanation
3 1 4 1 5   10  95    (3+1+4+1)*10+5
3 1 4 1 5   1   14    (3+1+4+1)*1+5
1           999 1     1
\$\endgroup\$
6
  • \$\begingroup\$ Can we take the list in reverse? \$\endgroup\$
    – user92069
    Jul 11, 2020 at 8:20
  • \$\begingroup\$ @Third-party'Chef' No. \$\endgroup\$
    – Bubbler
    Jul 11, 2020 at 8:26
  • \$\begingroup\$ I wonder if your J solution used mixed base conversion \$\endgroup\$
    – xnor
    Jul 11, 2020 at 9:37
  • \$\begingroup\$ Can we take the input as numbers instead of a single array? \$\endgroup\$ Jul 11, 2020 at 9:54
  • \$\begingroup\$ @HighlyRadioactive Yes, that's fine. \$\endgroup\$
    – Bubbler
    Jul 11, 2020 at 12:19

59 Answers 59

1
2
2
\$\begingroup\$

tinylisp, 58 bytes

(load library
(d S(q((A N)(i(t A)(a(*(h A)N)(S(t A)N))(h A

Try it online!

tinylisp, 78 65 bytes

(d S(q((A N)(i(t A)(i(h A)(a(S(c(s(h A)1)(t A))N)N)(S(t A)N))(h A

Try it online!

Solution without using library, which is only for *.

-13 bytes thanks to DLosc

\$\endgroup\$
2
  • 1
    \$\begingroup\$ The non-library version can be 65 bytes if you make the multiplication algorithm part of the main function. \$\endgroup\$
    – DLosc
    Feb 4, 2022 at 16:28
  • \$\begingroup\$ @DLosc that's incredibly clever. I have a lot of practice to do! \$\endgroup\$
    – Giuseppe
    Feb 4, 2022 at 17:47
2
\$\begingroup\$

Risky, 9 bytes

-_{1+0+00_?+0+?*?

Try it online!

\$\endgroup\$
2
\$\begingroup\$

C (gcc), 56 bytes

s,i;f(v,l,f)int*v;{for(i=0;i<l-1;s+=v[i++]);return s*f;}

Try It Online!

f takes a vector (v), the length of the vector (l) and the factor to multiply the vector with (f) as arguments. It sums up the values in the vector, except for the last one (in s) and returns the sum multiplied by the factor.

\$\endgroup\$
1
\$\begingroup\$

Zsh, 25 bytes

n=`<&0`
<<<$[0${@/#/*n+}]

Try it online!

Takes the list as arguments and N on stdin. Inspired by the JS answer. Prefix each element with *n+ and $[evaluate arithmetically]. We have to add a 0 to the start as well. This is one byte shorter than using the join flag <<<$[${(j:*n+:)@}]

Zsh -P, 24 bytes

a=(0 \*`<&0`+$@)
<<<$[a]

Try it online!

Alternate solution using the -P flag, which enables RC_EXPAND_PARAM to do the same thing.

\$\endgroup\$
1
\$\begingroup\$

Vimscript 36 Bytes

Disgusted to report that Arnauld's solution also works for vimscript.

let F={a,n->eval(join(a,"*".n."+"))}
\$\endgroup\$
1
\$\begingroup\$

PHP, 41 bytes

fn($a,$n)=>array_pop($a)+array_sum($a)*$n

Try it online!

Just trying to use all the built-ins!

\$\endgroup\$
1
\$\begingroup\$

T-SQL, 40 bytes

I am using a table instead of an array, sql doesn't have arrays

The test uses a temporary table instead of a real table, because of lack of permissions to create a table.

SELECT sum(a*@-i/@@rowcount*a*~-@)FROM t

Try it online

\$\endgroup\$
1
\$\begingroup\$

SimpleTemplate, 81 bytes

It's fairly chunky :/
Mostly due to limitations in my language...

{@eachargv.0}{@ifloop.last is equal0}{@set*_ _,argv.1}{@/}{@incby_ R}{@/}{@echoR}

Takes a string of numbers or an array as the first argument, and the n as the 2nd argument.

You can try this on http://sandbox.onlinephpfunctions.com/code/4c7290781560c876ff1e72e5d1680ed7b98861a3


Ungolfed:

The code above is a little weird to read...

Here's a more readable version:

{@set result 0}
{@each argv.0 as number}
    {@if loop.last is equal to false}
        {@set* number number, argv.1}
    {@/}
    {@inc by number result}
{@/}
{@echo result}

Notes:

  • {@set result 0} is optional, as {@inc} will create the variable, if it doesn't exist
  • {@each argv.0 as number} doesn't need need the as number, defaulting to the variable _ to store values
  • {@if loop.last is equal to false} uses the special variable loop to know if it is the last item in the {@each} Also, false is the same as 0.
  • {@set* number number, argv.1} multiplies number with argv.1 and stores it inside number. If number was an array, it would multiply with all the values.
  • {@inc by number result} will increment the variable result by number (effectivelly, result = result + number)
  • {@/} is usually optional, but, with this code, they are all required.
\$\endgroup\$
1
\$\begingroup\$

Perl 5 + -pi, 19 bytes

s/,/*$^I+/g;$_=eval

For example, for multiplicand 10, perl -pi10 -e's/,/*$^I+/g;$_=eval

Try it online. Idea stolen from this J answer. Accuracy improved by Dom Hastings in comments on this answer (many thanks!).

\$\endgroup\$
2
  • \$\begingroup\$ You need to take n from input too, it's not always 10! :) \$\endgroup\$ Jul 15, 2020 at 12:12
  • \$\begingroup\$ You can get the same byte-count using non-standard input for n (-i): Try it online! \$\endgroup\$ Jul 15, 2020 at 12:15
1
\$\begingroup\$

dc, 21 bytes

ss0[+z2<o]dso0rx*ls+p

Examples:

dc -e '10 3 1 4 1 5 ss0[+z2<o]dso0rx*ls+p'
95
dc -e '1 3 1 4 1 5 ss0[+z2<o]dso0rx*ls+p'
14
dc -e '999 1 ss0[+z2<o]dso0rx*ls+p'
1
\$\endgroup\$
1
\$\begingroup\$

Raku, 21 bytes

{*.join("*$_+").EVAL}

Try it online!

This works the same as the Perl 5 answer and also works with non-mutable lists, unlike the existing Raku answer, which is only one byte smaller than this.

Note: My previous answer of the same size does not work for singleton lists, which I've lodged an issue about.

\$\endgroup\$
1
\$\begingroup\$

excel, 25 bytes

Enter A followed by n in one column, followed by this formula

=SUM(R1:R[-3])*R[-1]+R[-2]

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Note: R1C1 Reference Style option must be checked. \$\endgroup\$ Jul 22, 2020 at 18:59
1
\$\begingroup\$

Lua, 58 bytes

r,t=0,{...}for i=2,#t-1 do
r=r+t[i]end print(r*t[1]+t[#t])

Try it online!

Having almost no array functions, Lua doesn't do too well in this challenge.

\$\endgroup\$
1
\$\begingroup\$

Scala, 22 bytes

a=>a.last+_*a.init.sum

This returns a List[Int] => Int => Int

Try it online

\$\endgroup\$
1
\$\begingroup\$

MATL, 9 bytes

*1G0)0Z(s

Try it online!

Explanation

*1G0)0Z(s
*          % Multiply the inputs and push it onto the stack
 1G        % Push first input onto the stack
   0)      % Replace top stack element with its last element
     0Z(   % Set last element of multiplied inputs to top element in stack
        s  % Replace top stack element with its sum
\$\endgroup\$
1
\$\begingroup\$

Wolfram Language (Mathematica), 16 bytes

a___~f~b_=+a#+b&

Try it online!

This one doesn't need a strange-looking input.

Takes input as f[A][n].


older, 17 bytes

#//.a_@b_:>a#2+b&

Try it online!

Takes a singly linked list as input: if X is a value and L is a list, X is the single-element list with element X, and X[L] is the list with element X, followed by the elements of L. For example, 3@1@4@1@5=3[1[4[1[5]]]] is the list with 3, 1, 4, 1, 5.

Per this discussion, we can take the first element with Head, and the tail with Last.

\$\endgroup\$
2
  • \$\begingroup\$ is {3@1@4@1@5,10} a valid input? If it is, nice job! I tried something similar but the best I could do was 24 bytes #/.{a__,b_}:>Tr@{a}#2+b& \$\endgroup\$
    – ZaMoC
    Jul 11, 2020 at 23:20
  • \$\begingroup\$ @J42161217 a flat input can get down to 18 byes by taking it in Dot or a Flat two-byte operator (a_.b_ is Times[Optional[a_],b_] rather than Dot[a_,b_]): Try it online! For a list, you can get 20: #/.{a__,b_}:>+a#2+b& \$\endgroup\$
    – att
    Jul 11, 2020 at 23:57
1
\$\begingroup\$

Rust, 45 bytes

|a,n|a.pop().unwrap()+a.iter().sum::<i64>()*n

Try it online

The expected argument types are a: &mut Vec<i64> and n: i64.

\$\endgroup\$
1
\$\begingroup\$

Charcoal, 10 9 bytes

I⁺⊟θ×η↨θ¹

Try it online! Link is to verbose version of code. Presumably Charcoal has the same problem as IO when it comes to summing empty lists. Edit: saved 1 byte by converting from base 1 instead. Explanation:

   θ        `A`
  ⊟         Remove last element
 ⁺          Added to
       θ    Remaining elements of `A`
      ↨ ¹   Take the sum by converting from base 1
    ×       Multiplied by
     η      `n`
I           Cast to string
            Implicitly print
\$\endgroup\$
1
\$\begingroup\$

Japt -h, 6 bytes

Ç+Ux*V

Try it

\$\endgroup\$
1
\$\begingroup\$

PowerShell Core, 29 bytes

param($a,$b)$a-join"*$b+"|iex

Try it online!

^ inspired by Arnauld's solution

My original one

PowerShell Core, 75 bytes

param($a,$b)(($a[($l=$a.Length-1)]+$b*($a[0..($l-1)]-join'+'|iex)),$a)[!$l]

Try it online!

\$\endgroup\$
0
1
\$\begingroup\$

Stax, 6 4 bytes

╡÷E@

Run and debug it

\$\endgroup\$
1
\$\begingroup\$

Factor + math.unicode, 23 bytes

[ dup pop -rot Σ * + ]

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Vyxal s, 5 bytes

*ṫ⁰/J

Try it Online!

\$\endgroup\$
1
\$\begingroup\$

Ly, 18 bytes

&n&spp&+>l<s>l*+u;

Try it online!

&n                 - read all the numbers into the stack
  &s               - save the entire stack to the backup cell
    pp             - delete top two entries on the stack
      &+           - sum the stack
        >l         - switch to clean stack, load original input
          <s       - switch back, save summary to backup cell
            >l     - switch stacks, load save sum of 2nd to N entries
              *    - multiple top two entries on stack
               +   - add top two stack entries
                u  - print top of stack as a number
                 ; - exit the code to avoid printing the rest of the stack
\$\endgroup\$
1
\$\begingroup\$

Arturo, 28 bytes

$[a,n][+last a n*sum chop a]

Try it

$[a,n][           ; a function taking args a and n
  +last a         ; add the last elt in a to
  n*sum chop a    ; n times the sum of a without its last elt
]                 ; end function
\$\endgroup\$
0
\$\begingroup\$

Io, 31 bytes

Saves a byte over the 32 byte solution. But it's boring.

method(a,N,a sum*N-a pop*(N-1))

Try it online!

Explanation

method(a, N,
    a sum * N         // Sum the input, multiply by N
  - a pop * (N - 1)   // Minus the last item, multiplied by N - 1
)

Io, 32 bytes

Just as comparison

method(a,N,a push(a pop/N)sum*N)

Try it online!

Explanation

method(a, N,
           a pop           // Extract the last item from the input list
                /N         // Divide it by N
    a push(       )        // And then put it back into the original list
                   sum     // Sum the list
                      *N   // Multiply the value by N
)
\$\endgroup\$
0
\$\begingroup\$

C (gcc), 53 bytes

Saved 2 bytes thanks to ceilingcat

s;f(a,n)int*a,n;{for(s=0;a[1];s+=*a++);return*a+s*n;}

Try it online!

\$\endgroup\$
0
0
\$\begingroup\$

Perl 6, 29 bytes

->$a,$b {$a.pop+([+] $a)*$b};

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ You can use $^a and $^b instead, as well as .sum, and the semi-colon is not needed, which ends up being the same as a previous Raku answer \$\endgroup\$
    – Jo King
    Aug 4, 2020 at 6:14
  • \$\begingroup\$ @JoKing Oh, my bad! Thanks for the tip, though - I'm still learning Raku. \$\endgroup\$
    – sugarfi
    Aug 4, 2020 at 16:31
0
\$\begingroup\$

TI-BASIC, 30 bytes (on-calc) / 37 bytes (as text)

Assumes list variable L₁ contains the array and variable N contains n.

dim(L₁
Nsum(L₁,1,Ans-1)+L₁(Ans

Explanation

  • dim(L₁: Get the size of L₁, to be used in the next line as Ans.
  • Nsum(L₁,1,Ans-1)+L₁(Ans: The sum( function has optional arguments to specify the beginning and end of a region of the list to be summed. The sum is implicitly multiplied by N, then added to the last element of the list, and implicitly printed.

Closing parentheses can be left out at the end of lines in TI-BASIC.

\$\endgroup\$
1
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.