34
\$\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

70 Answers 70

2
\$\begingroup\$

Pip, 10 bytes

a@v+b*$+Ha

Attempt This Online!

-2 from DLosc.

\$\endgroup\$
1
  • \$\begingroup\$ @RVa can be a@v; also, @< can be H if you use Pip 1.0: Attempt This Online \$\endgroup\$
    – DLosc
    Feb 4, 2022 at 16:36
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\$
2
\$\begingroup\$

Thunno 2 s, 4 bytes

×Ẹ¹÷

Attempt This Online!

Thunno 2, 5 bytes

µʋ¹×+

Attempt This Online!

Suggested by @noodleman.

Explanation

×Ẹ¹÷  # Implicit input
×     # Multiply each item in the list by the number
 Ẹ    # Dump onto stack, last item on top
  ¹÷  # Divide this number by the second input
      # Implicit output of summed stack
µʋ¹×+ # Implicit input
µʋ    # Right-reduce the input list by:
  ¹×  #  Multiply by the second input
    + #  And add this to the cumulative total
      # Implicit output
\$\endgroup\$
2
  • \$\begingroup\$ 5 bytes flagless µʋ¹×+ \$\endgroup\$
    – noodle man
    Jun 21, 2023 at 18:29
  • \$\begingroup\$ @noodleman thanks, updated \$\endgroup\$
    – The Thonnu
    Jun 21, 2023 at 18:48
2
\$\begingroup\$

TI-BASIC, 17 bytes

Input N
Nsum(Ans)-(N-1)Ans(dim(Ans

Takes input of \$A\$ in Ans.

Alternatives that are also 17 bytes:

Input N
sum(Ansmax(1,N(N>cumSum(1 or Ans
Input N
sum(AnsNaugment(1 or ΔList(Ans),{N⁻¹
\$\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\$

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\$

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
\$\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\$
1
\$\begingroup\$

JavaScript (Node.js), 33 bytes

n=>a=>a.reduceRight((x,c)=>x+c*n)

Attempt This Online!

Not as short as the eval solution but uses a very similar method.

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

Swift, 46 bytes

{a,n in a.dropLast().reduce(a.last!){$0+n*$1}}

Try it online!

Type signature: <C: BidirectionalCollection where C.Element: Numeric>(C, C.Element) -> C.Element. (That syntax isn't quite legal Swift for lack of generic lambdas, but you know what I mean.)

For each element ($1) in a except the last one, add n*$1 to the running total. The total starts at a.last instead of zero.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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