Code Golf Asked on October 27, 2021
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)?
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
Assumes list variable L₁
contains the array and variable N
contains n.
dim(L₁
Nsum(L₁,1,Ans-1)+L₁(Ans
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.
Answered by orangey on October 27, 2021
Answered by xigoi on October 27, 2021
Answered by wasif on October 27, 2021
Answered by chunes on October 27, 2021
Answered by Razetime on October 27, 2021
Ṫṭ×S
Ṫ 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:
S,¥/ḅ
/ 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.
Answered by Unrelated String on October 27, 2021
param($a,$b)$a-join"*$b+"|iex
^ inspired by Arnauld's solution
My original one
param($a,$b)(($a[($l=$a.Length-1)]+$b*($a[0..($l-1)]-join'+'|iex)),$a)[!$l]
Answered by Julian on October 27, 2021
Answered by MarcMush on October 27, 2021
b*$+@<a+@RVa
b*$+@<a+@RVa
b* Second argument(b) times
$+ Sum of elements of
@<a First argument list(a) without last element
+@RVa Plus first element of the reverse of a
Answered by Razetime on October 27, 2021
%@_2A<:.>2M3A[1A~M~]%WM:
Now it works properly on the testcases. Works on MAWP 1.1's integer input.
Answered by Razetime on October 27, 2021
^ ^
/l /+
/oop ^---^
^-----^ - /x
/ / ---
/arg /set
-----^-----^
/2 /+
--- ^---^
^- /1
^- ---
^-
/]
^---^
/ /2
/set---
^-----^
/x ^-
--- /]
^---^
^- /#
/ ---^
/set /
^-----^ /arg
- /+-----^
^---^ /2
/* - ---
^---^
^- /#
/x ^---
---/
/arg
^-----
/1
---
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
.
Answered by Jo King on October 27, 2021
Answered by sugarfi on October 27, 2021
->a,n{eval a*"*n+"}
Courtesy of petStorm.
Old answer:
n,*A,l=gets.split(' ').map(&:to_i)
p A.sum*n+l
Answered by Razetime on October 27, 2021
|a,n|a.pop().unwrap()+a.iter().sum::<i64>()*n
The expected argument types are a: &mut Vec<i64>
and n: i64
.
Answered by TehPers on October 27, 2021
Saved 2 bytes thanks to ceilingcat
s;f(a,n)int*a,n;{for(s=0;a[1];s+=*a++);return*a+s*n;}
Answered by kaadmy on October 27, 2021
*1G0)0Z(s
*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
Answered by Mukundan314 on October 27, 2021
^ ^ ^ ^ ^ ^ ^ ^ ^
/ -^ / / / -^ / / /
/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
--- ---
(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
Answered by MarcinKonowalczyk on October 27, 2021
Answered by user on October 27, 2021
r,t=0,{...}for i=2,#t-1 do
r=r+t[i]end print(r*t[1]+t[#t])
Having almost no array functions, Lua doesn't do too well in this challenge.
Answered by val is still with Monica on October 27, 2021
Enter A followed by n in one column, followed by this formula
=SUM(R1:R[-3])*R[-1]+R[-2]
Answered by Conor James Thomas Warford Hen on October 27, 2021
{*.join("*$_+").EVAL}
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.
Answered by Jo King on October 27, 2021
~:i;-1%{i*+}*
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
Answered by psIQos on October 27, 2021
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
Answered by Sandra on October 27, 2021
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
Answered by M L on October 27, 2021
-pi
, 19 bytess/,/*$^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!).
Answered by msh210 on October 27, 2021
Answered by M Smith on October 27, 2021
Solution:
{*|x+/y*-1_x}
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:
Answered by mkst on October 27, 2021
-2 bytes with help from Giuseppe
function(l,n)rev(l)%*%n^(seq(!l)>1)
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.
Answered by Robin Ryder on October 27, 2021
ṪṭSƊḅ
A dyadic Link accepting a list of numbers on the left and a number on the right which yields a number.
Ṫṭ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
Answered by Jonathan Allan on October 27, 2021
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.Answered by Ismael Miguel on October 27, 2021
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
Answered by t-clausen.dk on October 27, 2021
+⍣⎕/⎕
A full program, which pretty much works like the 3-byte J solution. Takes two lines of input, $A$ first and $n$ second.
+⍣⎕/⎕
⎕ ⍝ 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
1¨⍛,⊥0,⊣
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
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
Answered by Bubbler on October 27, 2021
Anonymous tacit infix function. Takes $A$ as left argument and $n$ as right argument.
⊢/+.×+×∘~
×∘~
$A×(1-n)$
+.×+
$big(sum_{i=1}^N A_i×nbig)+$
⊢/
rightmost element (lit. right-argument reduction)
So this effectively implements: $$ Bigg(bigg(sum_{i=1}^N A_i×nbigg)+A×(1-n)Bigg)_N\ bigg(sum_{i=1}^N A_i×nbigg)+A_N×(1-n)\ bigg(sum_{i=1}^N A_i×nbigg)+A_N-n×A_N\ bigg(sum_{i=1}^{N-1} A_i×nbigg)+A_N $$
Answered by Adám on October 27, 2021
{@^a.pop+$^b*@a.sum}
By using twigils, @^a
matches the first arg (the array), and $^b
the second (the multiplier).
Answered by user0721090601 on October 27, 2021
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:
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.
Answered by 640KB on October 27, 2021
Answered by 640KB on October 27, 2021
(lambda(n A)(+(car(last A))(* n(-sum(butlast A)))))
(38 bytes was the function body' size only.)
Answered by Daanturo on October 27, 2021
Disgusted to report that Arnauld's solution also works for vimscript.
let F={a,n->eval(join(a,"*".n."+"))}
Answered by Jhal on October 27, 2021
n=`<&0`
<<<$[0${@/#/*n+}]
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+:)@}]
-P
, 24 bytesa=(0 *`<&0`+$@)
<<<$[a]
Alternate solution using the -P flag, which enables RC_EXPAND_PARAM to do the same thing.
Answered by GammaFunction on October 27, 2021
a___~f~b_=+a#+b&
This one doesn't need a strange-looking input.
Takes input as f[A][n]
.
older, 17 bytes
#//.a_@b_:>a#2+b&
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
.
Answered by att on October 27, 2021
+*sPQEe
+*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
Answered by Mukundan314 on October 27, 2021
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.
Answered by Neil on October 27, 2021
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
Answered by Neil on October 27, 2021
Answered by Noodle9 on October 27, 2021
Answered by Mukundan314 on October 27, 2021
That was fun to find.
&+/
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.
Answered by xash on October 27, 2021
foldr1.((+).).(*)
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.
Answered by xnor on October 27, 2021
Saved 3 bytes thanks to @Mukundan314
Expects (A)(n)
.
A=>n=>eval(A.join`*n+`)
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.
Answered by Arnauld on October 27, 2021
Answered by ZaMoC on October 27, 2021
o +V*Ux
o +V*Ux
o // Pop and return last element of first input
+ // plus
V* // second input times
Ux // Sum of first input
Answered by Mukundan314 on October 27, 2021
-2 bytes thanks to @KevinCruijssen.
*`²÷O
* Multiply list by second operand
` Dump
÷ Divide the last item by
² the second operand
O Sum the stack
„²*ý.VO
„ 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
Answered by user92069 on October 27, 2021
Saves a byte over the 32 byte solution. But it's boring.
method(a,N,a sum*N-a pop*(N-1))
method(a, N,
a sum * N // Sum the input, multiply by N
- a pop * (N - 1) // Minus the last item, multiplied by N - 1
)
Just as comparison
method(a,N,a push(a pop/N)sum*N)
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
)
Answered by user92069 on October 27, 2021
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:
The pilcrow (¶) represents a newline (value 10) in the grid.
Answered by ovs on October 27, 2021
Answered by Dom Hastings on October 27, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP