# Add an array with itself

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!

• Isn't it a dupe? Commented Sep 18, 2017 at 23:32
• @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. Commented Sep 18, 2017 at 23:54
• 7 instead of -7 in test cases Commented May 22, 2022 at 19:15

# Ruby, 43 bytes

->a,n{b=[w=0]*n;a.map{|r|b[w%n]+=r;w+=1};b}


I wanted to outgolf at least python, but I couldn't, so here is the best I could do.

### How it works:

• create an array of size n filled with zeroes
• iterate on the input array, and calculate sums, repeat wrapping around the output array

Try it online!

# Julia 0.6, 49 bytes

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


Try it online!

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

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

# Javascript, 5957 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]

• You were beaten to it. Commented Sep 19, 2017 at 11:23
• @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.
– nl-x
Commented Sep 19, 2017 at 11:30
• How so? It's identical to yours, just more golfed. Functions only need to be assigned to a variable if they're recursive. Commented Sep 19, 2017 at 11:31
• 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.
– nl-x
Commented Sep 19, 2017 at 11:44
• Currying, like anonymous functions, is also perfectly valid. See here. Commented Sep 19, 2017 at 11:49

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

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

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


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

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.

# Factor + grouping.extras math.unicode, 47 bytes

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


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

# 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


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

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

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

# Thunno 2, 4 bytes

ẇ0Ƭʂ


Try it online!

#### Explanation

ẇ0Ƭʂ  # Implicit input - A (array), N (integer)
ẇ     # Split (A) into chunks of length (N)
0Ƭ   # Transpose the list with filler 0
ʂ  # Sum each inner list
# Implicit output


# Uiua, 6 bytes

/+⬚0↯~


Try it!

/+⬚0↯~
↯~  # reshape into matrix with number of columns indicated by input
⬚0    # filling excess elements with zeros
/+      # sum columns


# Julia 0.6, 28 bytes

V\n=1:n.|>i->sum(V[i:n:end])


Try it online!

also works in Julia 1.0+