25
\$\begingroup\$

Your challenge today is to take an array, split it into chunks, and add those chunks.

Here's how this works: Your program or function will be given an array of integers a and a chunk size L. The array should be split into arrays of size L, if the array length is not divisible by L then the array should have 0's appended to it so that it is evenly divisible. Once the array is chunked, all chunks are to be added together element-wise. The resulting array is then output.

You can assume L is greater than 0, and that a is nonempty. You cannot make the assumption that a's contents are positive.

Here's an example:

[1,2,3,4,5,6,7,8], 3 => [1,2,3]+[4,5,6]+[7,8,0] =>  [1+4+7,2+5+8,3+6+0] => [12,15,9]

Test cases:

Array                           Length   Output
[1]                             1        [1]
[1]                             3        [1,0,0]
[0]                             3        [0,0,0]
[1,2]                           3        [1,2,0]
[1,2]                           1        [3]
[-1,1]                          2        [-1,1]
[-7,4,-12,1,5,-3,12,0,14,-2]    4        [12,-1,0,1]
[1,2,3,4,5,6,7,8,9]             3        [12,15,18]

This is , fewest bytes wins!

\$\endgroup\$
3
  • \$\begingroup\$ Isn't it a dupe? \$\endgroup\$
    – sergiol
    Sep 18, 2017 at 23:32
  • 2
    \$\begingroup\$ @sergiol if you can find a question that this is a duplicate of, I will delete this post myself. However, as far as I can tell it is not a dupe. \$\endgroup\$
    – Pavel
    Sep 18, 2017 at 23:54
  • \$\begingroup\$ 7 instead of -7 in test cases \$\endgroup\$
    – Joao-3
    May 22, 2022 at 19:15

46 Answers 46

1
2
2
\$\begingroup\$

BQN, 8 bytesSBCS

+˝↑˙⊸⋈⊸⥊

Run online!

{+˝↑‿𝕩⥊𝕨} is 1 longer. BQN's reshape is very good.

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

PowerShell, 62 bytes

param($a,$l)1..$l|%{$y=--$_;($o=0)..$l|%{$o+=$a[$y+$_*$l]};$o}

Try it online!

We take input $array and $length. Then loop from 1 to $l. Each iteration we set helper $y to be one less than the current number (this is because PowerShell 0-indexes but the $length is in 1-indexing). Then we set our $output to 0 and loop again up to $l. Each inner iteration we're simply accumulating into $o the appropriately-indexed $array element. This leverages the fact that indexing past the end of the array returns $null and 0 + $null = 0.

Once the inner loop is done, we output $o and move on to the next chunk. The various outputs are left on the pipeline and output via implicit Write-Output happens on program completion.

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

Perl 5, 44 + 1 (-a) = 45 bytes

@r=(0)x($l=<>);map$r[$i++%$l]+=$_,@F;say"@r"

Try it online!

Edit: fixed the case where the length requested was smaller than the input array

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

Scala 2.12.2, 80 bytes

(a:Array[Int],b:Int)=>(0 to b-1).map(i=>a.indices.filter(_%b==i).collect(a).sum)

It is slightly shorter than the Java solution.

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

Javascript, 59 57 56 bytes

f=(a,l)=>(r=Array(l).fill(0),a.forEach((c,i)=>r[i%l]+=c),r)

usage

f([1,2,3,4,5,6,7,8], 3);
// returns [12, 15, 9]

edit 1

According to @Shaggy in the comments, the f= part is not needed if the function is not recursive. So:

(a,l)=>(r=Array(l).fill(0),a.forEach((c,i)=>r[i%l]+=c),r)

with usage off course of:

((a,l)=>(r=Array(l).fill(0),a.forEach((c,i)=>r[i%l]+=c),r))([1,2,3,4,5,6,7,8], 3)
// returns [12, 15, 9]

edit 2

Golfing down 1 more character, as the extra parenthesis are no longer needed then.

(a,l,r=Array(l).fill(0))=>a.forEach((c,i)=>r[i%l]+=c)||r

with usage off course of:

((a,l,r=Array(l).fill(0))=>a.forEach((c,i)=>r[i%l]+=c)||r)([1,2,3,4,5,6,7,8], 3)
// returns [12, 15, 9]
\$\endgroup\$
5
  • \$\begingroup\$ You were beaten to it. \$\endgroup\$
    – Shaggy
    Sep 19, 2017 at 11:23
  • \$\begingroup\$ @Shaggy I don't think that solution is correct as per the rules. Also he is leaving out the f= part that should count for more characters. \$\endgroup\$
    – nl-x
    Sep 19, 2017 at 11:30
  • \$\begingroup\$ How so? It's identical to yours, just more golfed. Functions only need to be assigned to a variable if they're recursive. \$\endgroup\$
    – Shaggy
    Sep 19, 2017 at 11:31
  • \$\begingroup\$ The assignment is a program or a function that returns the resulting array. This function returns another function that needs to be executed again. Also the f= part is needed to call the function. If it is not needed, I can also golf down 2 characters. \$\endgroup\$
    – nl-x
    Sep 19, 2017 at 11:44
  • \$\begingroup\$ Currying, like anonymous functions, is also perfectly valid. See here. \$\endgroup\$
    – Shaggy
    Sep 19, 2017 at 11:49
1
\$\begingroup\$

Common Lisp, 90 bytes

(lambda(a l)(dotimes(i(-(length a)l)(subseq a 0 l))(incf(elt a(mod i l))(elt a (+ l i)))))

Try it online!

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

POSIX shell, 45 bytes

This requires the utilities jot and rs to be installed, as well as the more common sed and bc. The chunk size is passed as the first argument, and the array as space-separated values on standard input

(jot -b0 $1;cat)|rs -tjg1 -C+ $1|sed s/.//|bc

The jot command generates a row full of zeros (in case the chunk size is smaller than the input); cat appends the input, then rs transforms that into the specified number of rows. Each line now begins with +, and bc won't accept that, so remove it with sed before performing the summation of each line.

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

Scala, 75 bytes

a=>n=>(a++Seq.fill(n-a.size/n)(0)).grouped(n).toSeq.transpose.map(_.sum)

To use this, you have to add a type:

val f:(Seq[Int]=>Int=>Seq[Int])=
    a=>n=>(a++Seq.fill(n-a.size/n)(0)).grouped(n).toSeq.transpose.map(_.sum)

f(Seq(1,2,3,4,5,6,7,8))(3) 
\$\endgroup\$
1
\$\begingroup\$

Pari/GP, 33 bytes

a->l->Vecrev(Polrev(a)%(x^l-1),l)

Converts a to a polynomial, mod x^l-1, and then converts it back to a list.

Try it online!

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

Julia 0.6, 49 bytes

V\n=sum(reshape([V;zeros(n-endof(V)%n,1)],n,:),2)

Try it online!

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

Add++, 25 bytes

D,f,@@*,d0b]*$@$+TbUpBcBs

Try it online!

How it works

First, we define our function \$f(a, x)\$. It takes two arguments (@@) and returns the entire stack (*), rather than the top element. Here, \$a\$ denotes the array of elements, such as \$a := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\$, and \$x\$ represents slice length, \$x := 4\$ for example. The stack is \$[a, x]\$ at the start of execution. We then duplicate \$x\$, and repeat \$[0]\$ \$x\$ times. We call this array \$z\$, rearrange the stack so it looks like \$[x, a, z]\$ and concatenate \$a\$ with \$z\$. This appends \$x\$ zeroes to the end of \$a\$.

Next, we take slices of length \$x\$ from \$a ^ \frown z\$. For the example inputs above, this would yield \$[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 0, 0], [0, 0]]\$. For every possible inputs, this yields an array where the final element always contains only superfluous zeroes, so we splat the elements of the array to the stack and remove the last element. Finally, we zip the arrays together and take the sum of each.

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

Factor + grouping.extras math.unicode, 47 bytes

[ [ 0 pad-groups ] keep group flip [ Σ ] map ]

enter image description here

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

R, 54 bytes

function(a,l,m=matrix(a,l))rowSums(m*(seq(m)<=seq(a)))

Try it online!

Somewhat based on Giuseppe's answer, but uses a different trick to counteract R's recycling the first elements of a to fill the last chunk.

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

C(GCC), 44 bytes

m(a,L,l,o)int*a,*o;{for(;l--;)o[l%L]+=a[l];}

Try it online It doesn't get more stupid than this :) In the tio version, i added a few macros, but they only help me do the tests in main more easily, and aren't used in the actual function. It modifies a given array instead of directly outputting one, because that's a real pain to do in c. It expects a zeroed array in o.

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

Desmos, 106 71 bytes

l=[1...s]
f(a,s)=[∑_{q=1}^{ceil(a.length/s)}join(a,l0)[qs-s+t]fort=l]

-35 bytes thanks to Aiden Chow

Try it on Desmos!

\$\endgroup\$
4
  • \$\begingroup\$ 94 bytes with various smaller golfs. \$\endgroup\$
    – Aiden Chow
    May 22, 2022 at 9:40
  • \$\begingroup\$ Actually, 86 bytes \$\endgroup\$
    – Aiden Chow
    May 22, 2022 at 9:48
  • \$\begingroup\$ Seems like you don't need to subtract mod(k,s): 75 bytes \$\endgroup\$
    – Aiden Chow
    May 22, 2022 at 17:21
  • \$\begingroup\$ Oh wait once you take out that, you don't even need k anymore: 71 bytes \$\endgroup\$
    – Aiden Chow
    May 22, 2022 at 17:23
0
\$\begingroup\$

Burlesque, 21 bytes

J0bcj.+2MVj_+jcotp)++

Try it online!

J    # Dup L
0bc  # Infinite list of zeros
j.+  # Select L 0s
2MV  # Put list at top of stack
j_+  # Append zeros
jco  # Split into chunks of length L
tp   # Transpose
)++  # Map sum
\$\endgroup\$
1
2

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.