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

33
\$\begingroup\$

J, 3 bytes

That was fun to find.

&+/

Try it online!

How it works

10 (&+/) 3 1 4 1 5 will bind 10 as an argument of + as 10&+, one verb that gets inserted between the elements of the list by /. So we have: 3 (10&+) 1 (10&+) 4 (10&+) 1 (10&+) 5. Now x n&v y means that y gets applied to n&v for x times. With J's right to left evaluation we get: to 5 add 1 times 10, add 4 times 10, add 1 times 10, add 3 times 10. A challenge made for J's stranger parts. :-) And because + is commutative, +&/ would also be a valid solution.

\$\endgroup\$
1
  • 6
    \$\begingroup\$ Perfect, you nailed it! \$\endgroup\$
    – Bubbler
    Jul 11, 2020 at 12:17
28
\$\begingroup\$

JavaScript (ES6),  28  23 bytes

Saved 3 bytes thanks to @Mukundan314

Expects (A)(n).

A=>n=>eval(A.join`*n+`)

Try it online!

How?

We simply join the input array with "*n+", so that [1,2,3] is turned into "1*n+2*n+3" and evaluate the resulting string.

\$\endgroup\$
1
  • 3
    \$\begingroup\$ I'm simultaneously amazed and disgusted. Good work! \$\endgroup\$
    – Jhal
    Jul 11, 2020 at 22:02
10
\$\begingroup\$

Haskell, 17 bytes

foldr1.((+).).(*)

Try it online!

It turns out this this was close to a port of the intended J solution. The pointfree function ((+).).(*) takes the argument n to the map \a b->a*n+b, that is, to add n times the left value to the right value. This creates the same "verb" as J used, and the foldr1 does the same a J's automatic right to left evaluation. It starts with the rightmost value in the list, which never gets multiplied by n, and applies it right-to-left, effectively increasing the sum so far with n times to the new element.

\$\endgroup\$
7
\$\begingroup\$

Python 3, 27 bytes

lambda a,n:a.pop()+sum(a)*n

Port of my Japt solution to python

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ Snap! Just wrote the exact same code without looking at any answers! \$\endgroup\$
    – Noodle9
    Jul 11, 2020 at 10:31
  • \$\begingroup\$ +1 for 2 min earlier \$\endgroup\$
    – ZaMoC
    Jul 11, 2020 at 11:29
6
\$\begingroup\$

Wolfram Language (Mathematica), 19 bytes

#2Tr@Most@#+Last@#&

Try it online!

\$\endgroup\$
5
\$\begingroup\$

Python 3, 27 bytes

lambda a,n:a.pop()+sum(a)*n

Try it online!

\$\endgroup\$
5
\$\begingroup\$

Clojure 41 bytes

#(+(last %1)(* %2(apply +(butlast %1))))

Unfortunately, + does have to be applyed.

Try It Online

\$\endgroup\$
3
  • 2
    \$\begingroup\$ Welcome to the community! Why not add a Try-It-Online link for your code so users can try it out :) \$\endgroup\$
    – mkst
    Jul 14, 2020 at 8:45
  • 1
    \$\begingroup\$ You can save 2 bytes by writing just % instead of %1, it is always recognized as the first argument, even when there are more. \$\endgroup\$
    – Kirill L.
    Jul 15, 2020 at 12:42
  • 1
    \$\begingroup\$ And another one by swapping the order of operands: tio.run/… \$\endgroup\$
    – Kirill L.
    Jul 15, 2020 at 12:49
4
\$\begingroup\$

05AB1E, 5 bytes

-2 bytes thanks to @KevinCruijssen.

*`²÷O

Try it online!

Explanation

*     Multiply list by second operand
 `    Dump
   ÷  Divide the last item by
  ²   the second operand
    O Sum the stack

05AB1E, 7 bytes

„²*ý.VO

Try it online!

Explanation

„       2-char string
 ²*     (Which does when evaluated) Multiply by the second input
   ý    Join the input list by this
    .V  Evaluate
      O Sum the resulting stack
\$\endgroup\$
1
4
\$\begingroup\$

APL (Dyalog Extended), 9 bytes (SBCS)

Anonymous tacit infix function. Takes \$A\$ as left argument and \$n\$ as right argument.

⊢/+.×+×∘~

Try it online!

×∘~\$A×(1-n)\$

+.×+\$\big(\sum_{i=1}^N A_i×n\big)+\$

⊢/ rightmost element (lit. right-argument reduction)

So this effectively implements: $$ \Bigg(\bigg(\sum_{i=1}^N A_i×n\bigg)+A×(1-n)\Bigg)_N\\ \bigg(\sum_{i=1}^N A_i×n\bigg)+A_N×(1-n)\\ \bigg(\sum_{i=1}^N A_i×n\bigg)+A_N-n×A_N\\ \bigg(\sum_{i=1}^{N-1} A_i×n\bigg)+A_N $$

\$\endgroup\$
1
  • \$\begingroup\$ @Bubbler Ugh, thanks, that'll be much harder to explain. Also, it isn't really related to my solution at all. You should self-answer with that, I guess. \$\endgroup\$
    – Adám
    Jul 13, 2020 at 7:55
4
\$\begingroup\$

APL (Dyalog Unicode), 5 bytes

+⍣⎕/⎕

Try it online!

A full program, which pretty much works like the 3-byte J solution. Takes two lines of input, \$A\$ first and \$n\$ second.

How it works

+⍣⎕/⎕
    ⎕  ⍝ Take the input A
   /   ⍝ Reduce by...
+      ⍝   Add the left argument
 ⍣⎕    ⍝   n times

For n=10 and A = 3 1 4 1 5, this becomes:
+⍣10/3 1 4 1 5
3 (+⍣10) 1 (+⍣10) 4 (+⍣10) 1 (+⍣10) 5
3 added 10 times to
         1 added 10 times to
                  4 added 10 times to
                           1 added 10 times to
                                    5

APL (Dyalog Extended), 8 bytes

1¨⍛,⊥0,⊣

Try it online!

A longer but more interesting one. A tacit dyadic function that takes \$A\$ on its left and \$n\$ on the right.

Uses mixed base conversion , which does the following:

Base:        1  1  1  ... 1    n
Digit value: n  n  n  ... n    1
Array value: 0  a1 a2 ... ax-1 ax
Total: a1n + a2n + ... + ax-1n + ax

How the code works

1¨⍛,⊥0,⊣  ⍝ Input: left=A, right=n
1¨        ⍝ An array of ones as long as A
  ⍛,      ⍝ Append n, which becomes the base
     0,⊣  ⍝ A prepended with single zero, which becomes the values
    ⊥     ⍝ Mixed base conversion as described above
\$\endgroup\$
1
  • \$\begingroup\$ Another interesting method could be (⎕⊥,)/⎕, but I don't think you can get rid of the brackets \$\endgroup\$
    – Jo King
    Jul 16, 2020 at 1:25
4
\$\begingroup\$

R, 37 36 35 bytes

-2 bytes with help from Giuseppe

function(l,n)rev(l)%*%n^(seq(!l)>1)

Try it online!

Reverse the vector, and perform dot product with the vector \$(n^0, n^1, n^1, \ldots,n^1) = (1, n, n,\ldots, n)\$.

I just discovered this behaviour of seq, which gains 1 byte on item 4 of this tip: seq(!l) is equivalent to seq(along.with = l) (giving the vector 1 2 3 ... length(l)) in all situations, even if l is of length 1. That is because !l is a logical, not an integer, and so we avoid the call to seq.int when l is a (length 1) integer.

\$\endgroup\$
4
  • \$\begingroup\$ If the list were guaranteed to be at least length 2, this would be a byte shorter, but as it is, it's longer by one instead. \$\endgroup\$
    – Giuseppe
    Jul 13, 2020 at 18:09
  • 1
    \$\begingroup\$ @Giuseppe Good old seq_along! I parlayed it into a 36-byter. Thanks! \$\endgroup\$ Jul 14, 2020 at 8:36
  • \$\begingroup\$ @Giuseppe seq(!l) works and is equivalent to seq(a=l), even if l is of length 1! \$\endgroup\$ Jul 15, 2020 at 10:59
  • 1
    \$\begingroup\$ Wow, it's been a while since I saw such a neat and applicable golfing trick! That's probably more due to my lack of participation here than anything else. \$\endgroup\$
    – Giuseppe
    Jul 15, 2020 at 18:15
4
\$\begingroup\$

Pyramid Scheme, 407 bytes

     ^      ^
    /l\    /+\
   /oop\  ^---^
  ^-----^ -  /x\
 / \   / \   ---
/arg\ /set\
-----^-----^
    /2\   /+\
    ---  ^---^
        ^-  /1\
       ^-   ---
      ^-
     /]\
    ^---^
   / \ /2\
  /set\---
 ^-----^
/x\   ^- 
---  /]\
    ^---^ 
   ^-  /#\
  / \  ---^
 /set\   / \
^-----^ /arg\
-    /+\-----^
    ^---^   /2\
   /*\  -   ---
  ^---^
 ^-  /#\
/x\ ^---
---/ \
  /arg\
 ^-----
/1\
---

Try it online!

Takes input through command arguments, with n as the first argument. This basically implements the algorithm:

i = 2
x = 0
o = 0
while args[i]:
  o += x*args[1]
  x = args[i]
  i += 1

print(o + x)

But with more nesting and some shortcuts, like using the variable 2.

\$\endgroup\$
4
\$\begingroup\$

K (oK), 14 13 bytes

Solution:

{*|x+/y*-1_x}

Try it online!

Explanation:

Couldn't figure out a smart way of solving this.

{*|x+/y*-1_x} / the solution
{           } / lambda taking implicity x, y
        -1_x  / drop (_) 1 element from end of x
      y*      / multiply by y
   x+/        / sum up with x as accumulator
 *|           / take last (reverse, first)

Notes:

  • -1 byte thanks to coltim - thanks!
\$\endgroup\$
1
  • 1
    \$\begingroup\$ You can trim a byte by doing {*|x+/y*-1_x} \$\endgroup\$
    – coltim
    Nov 19, 2020 at 14:04
3
\$\begingroup\$

Perl 5 + -pa -MList::Util+sum, 19 bytes

$_=pop(@F)+<>*sum@F

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ Did you mean -MList::Util=sum? \$\endgroup\$
    – msh210
    Jul 14, 2020 at 12:12
  • \$\begingroup\$ Interesting, I didn't know = would work there. I've always used + for places where spaces can't be used without quotes or to help precedence (e.g. /\d+\D/,say+($1)x$&). Looks like a bunch of things work though. Good to know, thanks! :) \$\endgroup\$ Jul 14, 2020 at 12:56
3
\$\begingroup\$

Japt, 7 bytes

o +V*Ux

Try it online!

Explanation

o +V*Ux
o         // Pop and return last element of first input
  +       // plus
   V*     // second input times
     Ux   // Sum of first input
\$\endgroup\$
3
\$\begingroup\$

Retina 0.8.2, 31 bytes

\d+
$*
1(?=.*,1*;(1*)|1*$)
$1
1

Try it online! Link includes test cases. Explanation:

\d+
$*

Convert to unary.

1(?=.*,1*;(1*)|1*$)
$1

Multiply all but the last element of A by n and delete A.

1

Take the sum and convert to decimal.

\$\endgroup\$
3
\$\begingroup\$

Pyth, 7 bytes

+*sPQEe

Try it online!

Explanation

+*sPQEe
    Q    # First input
   P     # Remove the last element
  s      # Sum elements
 *   E   # Multiply by the second input
+     e  # Add the last element of the first input
\$\endgroup\$
3
\$\begingroup\$

x86-16 machine code, 18 bytes

33 DB       XOR  BX, BX         ; clear running sum
49          DEC  CX             ; decrement array length
74 09       JZ   ADD_LAST       ; handle array length of 1 case
        LOOP_SUM:
AD          LODSW               ; load next value into AX
03 D8       ADD  BX, AX         ; BX = BX + AX
E2 FB       LOOP LOOP_SUM       ; keep looping
93          XCHG AX, BX         ; move sum into AX
F7 E2       MUL  DX             ; DX:AX = AX * DX
93          XCHG AX, BX         ; move result back to BX
        ADD_LAST:
AD          LODSW               ; load last value into AX
03 C3       ADD  AX, BX         ; AX = AX + BX
C3          RET                 ; return to caller

As a callable function: [SI] to input array, CX array length, DX = N. Output to AX.

Rather than make an elaborate test program, here's it being run using DOS DEBUG, entering the input array into memory and setting registers as they would be called:

enter image description here

Explanation of above:

Enter input array into memory address DS:200 as 16-bit, little-endian words:

-e 200 3 0 1 0 4 0 1 0 5 0

Point SI to this input array:

-r SI
:200

Set CX to array's length:

-r CX
:5

Set N to 10 (0xA in hex):

-r DX
:A

Execute and stop before last instruction (RET will "return to DOS" and clobber registers):

-g 111

Result is AX=005F or 95 in decimal.

\$\endgroup\$
3
\$\begingroup\$

Golfscript, 13 bytes

~:i;-1%{i*+}*

Try it online!

Explanation: ~ to convert string input to array and integer on stack. :i; assigns \$n\$ to i and pops value. -1% reverses the array and {i*+}* folds the array with (a, b) -> a*n + b

\$\endgroup\$
1
  • \$\begingroup\$ 11 bytes, if you take input in a different format \$\endgroup\$
    – user92069
    Jul 29, 2020 at 13:47
3
\$\begingroup\$

Emacs Lisp with dash library: 38 51 bytes

(lambda(n A)(+(car(last A))(* n(-sum(butlast A)))))

(38 bytes was the function body' size only.)

\$\endgroup\$
2
  • 1
    \$\begingroup\$ You forgot to add the last back in. \$\endgroup\$
    – Sandra
    Jul 15, 2020 at 16:06
  • \$\begingroup\$ My bad, unfortunately the answer is now much longer. \$\endgroup\$
    – Daanturo
    Jul 16, 2020 at 0:55
3
\$\begingroup\$

Pyramid Scheme, 7747 3668 1985 1732 1619 bytes

Edits

  • -4079 bytes by giving the variables shorter names... 😅
  • -1638 bytes by doing some more manual optimisation
  • -253 bytes by using more 0-height trees
  • -113 bytes because out can output the final result directly
    ^  ^        ^       ^        ^  ^        ^        ^        ^
   / \ -^      / \     / \      / \ -^      / \      / \      / \
  /set\ -^    / do\   /set\    /   \ -^    /set\    /   \    /out\
 ^-----^ -^  ^-----^ ^-----^  / set \ -^  ^-----^  /     \   -----^
/l\   / \ -^/c\   ^-/n\   ^- ^-------^ -^/i\   ^- / loop  \      /+\
---  /arg\^----  ^- ---  ^- /N\     /#\^----  ^- ^---------^    ^---^
    ^------^    / \     /-\ ---    ^----^    ^- / \       / \  /s\ /#\
   / \    ^-   ^---^   ^---^      / \  ^-   ^- /<=>\     ^---^ --- ---^
  /99 \  ^-   / \ / \ /n\ /1\    /arg\^-   ^- ^-----^   / \ / \      / \
  ----- ^-   ^---/   \--- ---   ^------^  ^- /i\   /0\ ^---/set\    /arg\
       ^-   / \  -----^        /n\    ^- /-\ ---   ---/ \ ^-----^   -----^
      ^-   ^---      / \       ---   ^- ^---^        ^---/s\   / \      /-\
     ^-   / \       /set\           ^- /n\ /1\      / \  ---  / + \    ^---^
    ^-   /set\     ^-----^         / \ --- ---     ^---      ^-----^  /n\ /1\
   ^-   ^-----^   /c\   /!\       /set\           / \       /s\   /*\ --- ---
   -^  /n\   /+\  ---  ^---      ^-----^         /set\      ---  ^---^
   / \ ---  ^---^     /=\       /s\   /0\       ^-----^         /#\ /N\
  /set\    /n\ /1\   ^---^      ---   ---      /i\   /-\       ^--- ---
 ^-----^   --- ---  / \ /l\                    ---  ^---^     / \
/n\   /0\          /arg\---                        /i\ /1\   /arg\
---   ---         ^-----                           --- ---  ^-----
                 /n\                                       /i\
                 ---                                       ---

Try it online!

Explanation

(set nil (arg 99)) // Make nil

// Count the number of input arguments - n
(set nargin 0)
(do
    cond
    (
        (set nargin (+ nargin 1))
        (set cond (! (= (arg nargin) nil)))
    )
)
(set nargin (- nargin 1))

(set N (# (arg nargin))) // N - the number all but last of the array elements is getting multiplied by

// Add all but last elements of A
(set sum 0)
(set i (- nargin 1))
(loop
    (<=> i 0)
    (
        (set i (- i 1))
        (set sum (+ sum (* (# (arg i)) N))) // A[i] multiplied by N
    )
)
(set sum (+ sum (# (arg (- nargin 1))))) // Add the last element of A
(out sum) // Print
\$\endgroup\$
1
  • \$\begingroup\$ Some golfing for 1042 bytes. There's more you can do though (especially with that first do loop) \$\endgroup\$
    – Jo King
    Aug 4, 2020 at 8:46
3
\$\begingroup\$

Ruby, 46 19 bytes

->a,n{eval a*"*n+"}

Courtesy of petStorm.

Old answer:

n,*A,l=gets.split(' ').map(&:to_i)
p A.sum*n+l
\$\endgroup\$
2
  • 1
    \$\begingroup\$ 19 bytes, as an anonymous function \$\endgroup\$
    – user96495
    Aug 2, 2020 at 14:11
  • \$\begingroup\$ I should use anonymous functions more. Thanks! \$\endgroup\$
    – Razetime
    Aug 4, 2020 at 3:43
3
\$\begingroup\$

MAWP, 26 bytes

%@_2A<\:.>2M3A[1A~M~]%\WM:

Now it works properly on the testcases. Works on MAWP 1.1's integer input.

Try it!

\$\endgroup\$
2
  • \$\begingroup\$ The new program works now. Only took 6 days! \$\endgroup\$
    – Razetime
    Aug 31, 2020 at 4:16
  • \$\begingroup\$ +1 for persistence! \$\endgroup\$
    – Dingus
    Aug 31, 2020 at 4:28
3
\$\begingroup\$

Jelly, 4 bytes

Ṫṭ×S

Try it online!

Ṫ       Pop the last element of the left argument,
 ṭ      append it to
  ×     the right argument times what's left of the left argument,
   S    and sum.

A more fun solution, which borrows Jonathan Allan's base conversion trick:

Jelly, 5 bytes

S,¥/ḅ

Try it online!

   /     Reduce the left argument by
 ,       pair right with
S ¥      the sum of left,
    ḅ    and convert from base right.

Bonus: Ä-.ịḅ’} is a whole 7 bytes, and doesn't even work if the left argument only has one element, but it's just kind of funny.

\$\endgroup\$
2
\$\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\$
2
\$\begingroup\$

Raku, 20 bytes

{@^a.pop+$^b*@a.sum}

By using twigils, @^a matches the first arg (the array), and $^b the second (the multiplier).

Try it online!

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

Jelly, 5 bytes

ṪṭSƊḅ

A dyadic Link accepting a list of numbers on the left and a number on the right which yields a number.

Try it online!

ṪṭSƊḅ - Link: list of numbers, A; number n
   Ɗ  - last three links as a monad - f(A):
Ṫ     -   remove the tail (of A) and yield its value
  S   -   sum (the remaining elements in A)
 ṭ    -   tack -> [sum_of_remaining, tail]
    ḅ  - convert from base (n) -> n×sum_of_remaining+1×tail
\$\endgroup\$
2
\$\begingroup\$

Q'Nial, 33 bytes (20 bytes without operator definition)

s is op n a{+link[n*front,last]a}   %full operator definition

+link[n*front,last]a                %simple function

Explanation:

+                                   sum, reduce by +
 link                               list of the items of the argument
     [                              atlas (argument of link operation), point-free notation
      n*                            n *
        front                       all elements but the last of the argument
             ,
              last                  last element of the argument
                  ]                 end atlas
                   a                array a (argument of atlas)

Intermediate results, for n=10 and a=3 1 4 1 5

         10 s 3 1 4 1 5
or
         s 10 (3 1 4 1 5)

or
         +link[10*front,last]3 1 4 1 5

         [n*front,last] a
+-------------+-+
|+--+--+--+--+|5|
||30|10|40|10|| |
|+--+--+--+--+| |
+-------------+-+

         link[n*front,last] a
+--+--+--+--+-+
|30|10|40|10|5|
+--+--+--+--+-+

         +link[n*front,last]a
95
\$\endgroup\$
2
\$\begingroup\$

Befunge-98 (PyFunge), 29 27 bytes

j&10p#v&\10g*\4
_\.@  >+\:#

Try it online! Input is first N, then A. Note that there has to be a trailing space.

Animation of the code:

enter image description here

The pilcrow (¶) represents a newline (value 10) in the grid.

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

Julia 1.0, 21 19 bytes

A$n=pop!(A)+sum(A)n

Try it online!

\$\endgroup\$

Your Answer

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

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