# 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        
                             3        [1,0,0]
                             3        [0,0,0]
[1,2]                           3        [1,2,0]
[1,2]                           1        
[-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? 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. Sep 18, 2017 at 23:54
• 7 instead of -7 in test cases May 22 at 19:15

# Python 3, 6765 42 bytes

Uses the fact that the sum of an empty array is 0

lambda x,y:[sum(x[i::y])for i in range(y)]


Try it online!

# MATL, 4 bytes

e!Xs


Try it online!

First bit of MATL code I've written! Takes two inputs, a as a row vector (comma-separated) and l as a number. Works out to be

e          # reshape a into l rows (auto pads with 0)
!         # transpose
Xs       # sum down the columns


# Jelly, 7 6 bytes

1 byte thanks to Dennis.

;0$¡sS  Try it online! • With a newer version of Jelly, you can do Ż¡sS (equivalent to 0;$¡sS). Jun 30, 2018 at 18:53

## Java 7, 86 bytes

No fancy folds or matrices, just a good ol' fashioned for loop :)

int[]o(int[]a,int l){int i=0,o[]=new int[l];for(;i<a.length;)o[i%l]+=a[i++];return o;}


Try it on Ideone

Lined:

int[]o(int[]a,int l){
int i=0,
o[]=new int[l];
for(;i<a.length;)
o[i%l]+=a[i++];
return o;
}

• and with the good ol' fashioned Java 7 (instead of 8). ;) Sep 19, 2017 at 6:53

# Python 2, 49 bytes

lambda x,n:map(sum,zip(*zip(*[iter(x+n*)]*n)))


Try it online!

# JavaScript (ES6), 51 bytes

a=>n=>a.map((v,i)=>o[i%n]+=v,o=Array(n).fill(0))&&o


Takes input in currying syntax: f([1,2])(3).

## Test Cases

let f=
a=>n=>a.map((v,i)=>o[i%n]+=v,o=Array(n).fill(0))&&o

;[[, 1], [, 3], [, 3], [[1,2], 3], [[1,2], 1], [[-1,1], 2], [[-7,4,-12,1,5,-3,12,0,14,-2], 4], [[1,2,3,4,5,6,7,8,9], 3]]
.forEach(([A,N])=>console.log(${JSON.stringify(A)},${N} -> ${f(A)(N)})) .as-console-wrapper{max-height:100%!important} • (a,n,o=[])=>a.map((v,i)=>o[i%n]=~~o[i%n]+v)&&o – Oki Sep 18, 2017 at 20:15 • @Oki Two bytes shorter: a=>n=>a.map((v,i)=>o[i%=n]=~~o[i]+v,o=[])&&o, but it doesn't add the required zero-padding. Sep 18, 2017 at 20:18 • f= should be part of your character count. – nl-x Sep 19, 2017 at 11:33 • @nl-x Anonymous functions are allowed by default, so as long as I'm not using the function name in my code, f= is not needed. Heres one post on meta about this. Sep 19, 2017 at 11:46 • @nl-x: No, it shouldn't; a function need only be named if it's recursive (or, maybe, a quine). If it's not then an anonymous function is perfectly valid. See here. Sep 19, 2017 at 11:47 # Mathematica, 27 bytes Mathematica almost had a builtin for this Total@Partition[##,#2,1,0]&  Try it on Wolfram Sandbox ### Usage Total@Partition[##,#2,1,0]&[{-7, 4, -12, 1, 5, -3, 12, 0, 14, -2}, 4]  {12, -1, 0, 1} ### Explanation Total@Partition[##,#2,1,0]& Partition[##,#2,1,0] (* Partition the first input into sublists of length second input, using offset second input, and right-pad zeroes for incomplete partitions *) Total@ (* Add all *)  • Your link ain't working. Sep 19, 2017 at 13:45 • @Shaggy you have to manually copy and paste the code. Wolfram Sandbox does not support pre-filled inputs. Sep 19, 2017 at 13:47 # Mathematica, 58 bytes Total@Partition[PadRight[#,(s=Length@#)+Mod[-s,#2]],{#2}]&  Input [{1},3] Output {1,0,0} • this works for ,3 You can test it here sandbox.open.wolframcloud.com by adding input at the end of the code and pressing shift+enter Sep 18, 2017 at 19:17 # Husk, 9 bytes S↑ȯ¡¬Fż+C  Try it online! ### Explanation  C Cut into lists of length n Fż+ Sum them element-wise ȯ¡¬ Append infinitely many 0s S↑ Take the first n elements  # Perl 6, 36 bytes {[Z+] flat(@^a,0 xx$^b*2).rotor($b)}  Test it ## Expanded: { # bare block lambda with 2 placeholder parameters ｢@a｣, ｢$b｣
[Z+]
flat(
@^a,         # declare and use the first parameter
0 xx $^b * 2 # 0 list repeated 2 * the second parameter ) .rotor($b)     # split into chunks that are the size of the second param
}

[1,2], 3

( [1,2], (0,0,0,0,0,0) ) # @^a,0 xx$^b*2 (1,2,0,0,0,0,0,0) # flat(…) ( (1,2,0), (0,0,0) ) # .rotor($b) # (drops partial lists)
(1,2,0)                  # [Z+]


# APL (Dyalog), 22 bytes

Takes l as left argument and a a right argument.

{+⌿s⍴⍵↑⍨×/s←⍺,⍨⌈⍺÷⍨≢⍵}


Try it online!

{} anonymous function where ⍺ is the left argument (l) and ⍵ the right argument (a).

≢⍵ tally (length) of a

⍺÷⍨ divide by l

⌈ ceiling (round up)

⍺,⍨ append l

s← store in s (for shape)

×/ product of that (i.e. how many integers are needed)

⍵↑⍨ take that many integers from a (padding with zeros)

s⍴reshape to shape s (rows, columns)

+⌿ columnar sums

a%l=[sum$map((0:a)!!)[i,l+i..length a]|i<-[1..l]]  Try it online! • I don't know if I'm allowed to submit a solution in a language that has already been done, so I'll post my solution here: (79 bytes) l%a|l>length a=t|1>0=zipWith(+)t$l%drop l a where t=take l$a++repeat 0 May 22 at 15:45 • @Itay123 Posting your own Haskell solution is perfectly fine! As per our Help center (and meta consensus), an answer only needs to be a valid solution of the challenge and make some effort towards the winning criteria. It does not have to be the shortest solution, and for me it's always interesting to see different approaches. So please go ahead and post your answer! May 23 at 16:29 # Perl 6, 40 bytes {[Z+] (|@^a,|(0 xx*)).rotor($^l)[0..@a]}


Try it online!

If you like the number 42, you can swap the * for an ∞. That will make it 42 bytes :—).

Explanation:

{[Z+] (|@^a,|(0 xx*)).rotor($^l)[0..@a]} The whole function { } Anonymous block ( , ) List with 2 elements @^a The first argument (it is a list) (0 xx*) Infinite list of zeroes | | Flatten both of the lists into the larger list. .rotor($^l)          Split the list into a list of lists, each (the second argument) long.
[0..@a]   Only the first (1 + length of the first argument) of them.
[Z+]                                    Add the corresponding elements up.


The magic behind the last "add up" is that the operator is a "reduce with zip with +". By the way, this would break down if we used it only on a list with 1 list inside, but that never happens if the original list was non-empty (due to the second-to-last row). Also note that we end up taking not only @a, but @a * $l items. Fortunately we added only zeroes which won't affect the final result. # Pyth, 8 bytes m+F%Q>vz  Try it here! # Pyth, 10 bytes sMCc.[EZQQ  Try it here! # Explanation ### Explanation #1 m+F%Q>vz Full program. Q means input. m Map over the implicit range [0, input_1), with a variable d. >vz All the elements of input_2 after d; input_2[d:] in Python. %Q Every Qth element of ^. +F Sum. Implicitly output the result.  ### Explanation #2 sMCc.[EZQQ Full program. .[E Pad the second input to the right, with repeated copies of... Z ... Zero (0), up to the nearest multiple of... Q ... The first input. c Q Chop into chunks of length equal to the first input. C Matrix transpose. Get all the columns of the nested list. sM Sum each. Output (implicitly).  • How about something like this: sM.TcEQ Sep 18, 2017 at 19:35 • @Jakube That is incorrect, as you have to pad with zeros first. That was Leaky's initial attempt, but would fail for , 3, which would give  instead of [1, 0, 0]. Sep 18, 2017 at 19:36 • Sorry, my mistake. Sep 18, 2017 at 20:42 # J, 15 12 bytes ]{.+/@(]\~-)  Try it online! ## Explanation ]{.+/@(]\~-) Input: array A (LHS), chunk size L (RHS) - Negate L ]\~ Take each non-overlapping sublist of size L in A +/@ Reduce the columns by addition ] Get L {. Take that many, filling with 0's  • Any reason we can't do away with the boxes? What about: [:+/-@[[\]? Sep 19, 2017 at 0:16 • @Jonah If the chunk size is larger than the length of the input array, it won't be zero-padded. Sep 19, 2017 at 0:42 • Nice edit -- much cleaner now. Sep 19, 2017 at 5:42 # R, 62 57 bytes -5 bytes thanks to user2390246 function(a,l)rowSums(matrix(c(a,rep(0,l-sum(a|1)%%l)),l))  Try it online! Updated since it no longer has to handle the empty case. pads a with zeros, constructs a matrix of l rows, and computes and returns the row sums. • 57 bytes Sep 19, 2017 at 9:15 • @user2390246 of course! I had that in an older version when we had to handle the empty case but this one was my "primary" and I didn't think to try that again. Sep 19, 2017 at 13:07 # 05AB1E, 8 bytes ô0ζO²Å0+  Try it online! ô0ζO²Å0+ Full program ô Push <1st input> split into a list of <2nd input> pieces 0ζ Zip sublists with 0 as a filler O Sum each sublist --- from here, the program handles outputs shorter than the required length ²Å0 Push a list of zeros of length <2nd input> + Sum the result with that list  # 05AB1E, 8 bytes Å0+¹ô0ζO  Try it online! Å0 # Push an arrary of all 0s with length l + # Add that to the array ¹ô # Split into chunks of length l 0ζ # Zip, padding with 0s O # Sum each chunk  • Almost identical to my own solution: codegolf.stackexchange.com/a/143186/73296 Sep 19, 2017 at 13:31 • @scottinet I must have missed that. They are different enough that I'll leave mine and upvote yours :) Sep 19, 2017 at 14:23 • I don't really mind, just wanted to point that out :) Sep 19, 2017 at 14:25 • @scottinet It is interesting that you can rearrange the operations and come out with the same byte count and almost identical bytes used (¹ vs ²) Sep 19, 2017 at 14:30 # Vyxal, 7 bytes ẇR∆ZR∩Ṡ  Try it Online! • afaict the zfilling is unecessary as the missing zeroes are simply ignored May 22 at 1:08 • @emanresuA that would fail on case [1,2], 3 => [1,2,0]. May 22 at 1:09 # SOGL V0.12, 14 bytes l⁵%⁵κ{0+}nI⌡∑¹  Try it Here! or Try all the test-cases. this is written as an unnamed function and expects chunk length; array on the stack. Explanation: padding zeroes l get the array's length ⁵% modulo the chunk length ⁵κ chunk length - result of above { } that many times 0+ append a 0 to the array adding the array together n split into the chunks I rotate clockwise ⌡ for each ∑ sum ¹ wrap the results in an array  • What's the F for in the Try it Here code you linked? Sep 18, 2017 at 19:47 • @Pavel the functions name. The same as in JS f=a=>a+2 the f= part isn't counted - in SOGL F\n isn't counted. Sep 18, 2017 at 19:48 # 05AB1E, 12 bytes gs÷*+Å0¹+ôøO  Try it online! ### Explanation gs÷*+Å0¹+ôøO g # Get the length of the first input (the array) s # Push the second input on top of the result ÷ # integer divide the two values * # Multiply with the second input (the length)... + # and add the second input to the result Å0 # Create a list of zeros with that length ¹+ # Add it to the first input ô # And finally split it into chunks of the input length... ø # ...transpose it... O # and sum each resulting subarray # Implicit print  ## Mathematica, 43 bytes Plus@@#~ArrayReshape~{⌈Tr[1^#]/#2⌉,#2}&  # Husk, 10 bytes Fż+So:R0C  Try it online! ### Ungolfed/Explanation  -- implicit inputs n & xs | 3 [1,2,3,4] S C -- cut xs into sublists of length n & ... | [[1,2,3], ] (:R0) -- ... prepend [0,...,0] (length n) | [[0,0,0], [1,2,3], ] F -- accumulate the sublists with | ż+ -- element-wise addition | [0+1+4, 0+2, 0+3]  # Clojure, 42 bytes #(apply map +(partition %2 %2(repeat 0)%))  Try it online! # Stacked, 24 bytes [:@z#<[0 z rpad]map sum]  Try it online! ## Explanation [:@z#<[0 z rpad]map sum] [ ] anonymous function :@z stores TOS as z (the length) #< cut STOS in TOS slices [ ]map for each slice 0 z rpad pad the slice with z zeroes sum] summate all inner slices  # Java (OpenJDK 8), 64 bytes n->a->{int k=0,r[]=new int[n];for(int i:a)r[k++%n]+=i;return r;}  Try it online! # Japt, 7 bytes Man, I fought with the wrong Japt method for far too long trying to get it to work for the , 3 test case in a reasonable amount of bytes! VÆëVX x  Try it ## Explanation Implicit input of array U and integer V. VÆ  Generate an array of integers from 0 to V-1 and pass each through a function with X being the current element. ëVX  Grab every Vth element of U, beginning at index X. x  Reduce that array by addition. # C, (GCC) 101 86 Bytes Try it online! f(int*a,int l,int s,int*m){if(s){int i=l;while(i&&s){m[l-i--]+=*a++;s--;}f(a,l,s,m);}}  ## Usage int main() { int l = 3; int a = {1,2,3,4,5,6,7,8}; int *m = (int *)malloc(sizeof(int) * l); f(a, l, 8, m); for (int i=0; i<3; i++) { printf("%d, ",m[i]); } }  Note that you have to pass in the length of the array (s) and a new dynamic array on the heap (m). • Jan 20, 2018 at 12:18 # BQN, 8 bytesSBCS +˝↑˙⊸⋈⊸⥊  Run online! {+˝↑‿𝕩⥊𝕨} is 1 longer. BQN's reshape is very good. # 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.