# Sum the array times n, except the last

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

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

• Can we take the list in reverse?
– user92069
Jul 11, 2020 at 8:20
• @Third-party'Chef' No. Jul 11, 2020 at 8:26
• I wonder if your J solution used mixed base conversion
– xnor
Jul 11, 2020 at 9:37
• Can we take the input as numbers instead of a single array? Jul 11, 2020 at 9:54
• @HighlyRadioactive Yes, that's fine. Jul 11, 2020 at 12:19

# 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

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

# Risky, 9 bytes

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


Try it online!

# 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.

# Zsh, 25 bytes

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


Try it online!

<<<$[a]  Try it online! Alternate solution using the -P flag, which enables RC_EXPAND_PARAM to do the same thing. # Vimscript 36 Bytes Disgusted to report that Arnauld's solution also works for vimscript. let F={a,n->eval(join(a,"*".n."+"))}  # PHP, 41 bytes fn($a,$n)=>array_pop($a)+array_sum($a)*$n


Try it online!

Just trying to use all the built-ins!

# 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

# 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.

Ungolfed:

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

{@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.

# 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!).

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

## 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


# 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. ## excel, 25 bytes Enter A followed by n in one column, followed by this formula =SUM(R1:R[-3])*R[-1]+R[-2] • Note: R1C1 Reference Style option must be checked. Jul 22, 2020 at 18:59 # 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. # Scala, 22 bytes a=>a.last+_*a.init.sum  This returns a List[Int] => Int => Int Try it online # 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  # 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. • 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& Jul 11, 2020 at 23:20 • @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& – att Jul 11, 2020 at 23:57 # 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. # Charcoal, 10 9 bytes Ｉ⁺⊟θ×η↨θ¹  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 Ｉ Cast to string Implicitly print  # Japt-h, 6 bytes Ç+Ux*V  Try it # 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! # Stax, 6 4 bytes ╡÷E@  Run and debug it # Factor + math.unicode, 23 bytes [ dup pop -rot Σ * + ]  Try it online! # Vyxals, 5 bytes *ṫ⁰/J  Try it Online! # 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  # 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  # 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 )  # 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! # Perl 6, 29 bytes ->$a,$b {$a.pop+([+] $a)*$b};


Try it online!

• 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
– Jo King
Aug 4, 2020 at 6:14
• @JoKing Oh, my bad! Thanks for the tip, though - I'm still learning Raku. Aug 4, 2020 at 16:31

# 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.