27
\$\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
    Commented 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
    Commented Sep 18, 2017 at 23:54
  • \$\begingroup\$ 7 instead of -7 in test cases \$\endgroup\$
    – Joao-3
    Commented May 22, 2022 at 19:15

49 Answers 49

13
\$\begingroup\$

Python 3, 67 65 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!

\$\endgroup\$
0
11
\$\begingroup\$

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

Jelly, 7 6 bytes

1 byte thanks to Dennis.

;0$¡sS

Try it online!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ With a newer version of Jelly, you can do Ż¡sS (equivalent to 0;$¡sS). \$\endgroup\$ Commented Jun 30, 2018 at 18:53
6
\$\begingroup\$

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 *)
\$\endgroup\$
2
  • \$\begingroup\$ Your link ain't working. \$\endgroup\$
    – Shaggy
    Commented Sep 19, 2017 at 13:45
  • 1
    \$\begingroup\$ @Shaggy you have to manually copy and paste the code. Wolfram Sandbox does not support pre-filled inputs. \$\endgroup\$ Commented Sep 19, 2017 at 13:47
5
\$\begingroup\$

Python 2, 49 bytes

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

Try it online!

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

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], 1], [[1], 3], [[0], 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}

\$\endgroup\$
5
  • \$\begingroup\$ (a,n,o=[])=>a.map((v,i)=>o[i%n]=~~o[i%n]+v)&&o \$\endgroup\$
    – Oki
    Commented Sep 18, 2017 at 20:15
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ Commented Sep 18, 2017 at 20:18
  • \$\begingroup\$ f= should be part of your character count. \$\endgroup\$
    – nl-x
    Commented Sep 19, 2017 at 11:33
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ Commented Sep 19, 2017 at 11:46
  • 1
    \$\begingroup\$ @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. \$\endgroup\$
    – Shaggy
    Commented Sep 19, 2017 at 11:47
4
\$\begingroup\$

Mathematica, 58 bytes

Total@Partition[PadRight[#,(s=Length@#)+Mod[-s,#2]],{#2}]&

Input

[{1},3]

Output

{1,0,0}

\$\endgroup\$
1
  • \$\begingroup\$ this works for [1],3 You can test it here sandbox.open.wolframcloud.com by adding input at the end of the code and pressing shift+enter \$\endgroup\$
    – ZaMoC
    Commented Sep 18, 2017 at 19:17
4
\$\begingroup\$

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;
}
\$\endgroup\$
1
  • 2
    \$\begingroup\$ and with the good ol' fashioned Java 7 (instead of 8). ;) \$\endgroup\$ Commented Sep 19, 2017 at 6:53
4
\$\begingroup\$

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

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+]
\$\endgroup\$
4
\$\begingroup\$

BQN, 8 bytesSBCS

+˝↑˙⊸⋈⊸⥊

Run online!

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

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

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

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

Haskell, 59 49 bytes

a%l=[sum$map((0:a)!!)[i,l+i..length a]|i<-[1..l]]

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ 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 \$\endgroup\$
    – Itay123
    Commented May 22, 2022 at 15:45
  • 1
    \$\begingroup\$ @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! \$\endgroup\$
    – Laikoni
    Commented May 23, 2022 at 16:29
3
\$\begingroup\$

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.

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

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). 
\$\endgroup\$
3
  • \$\begingroup\$ How about something like this: sM.TcEQ \$\endgroup\$
    – Jakube
    Commented Sep 18, 2017 at 19:35
  • \$\begingroup\$ @Jakube That is incorrect, as you have to pad with zeros first. That was Leaky's initial attempt, but would fail for [1], 3, which would give [1] instead of [1, 0, 0]. \$\endgroup\$
    – Mr. Xcoder
    Commented Sep 18, 2017 at 19:36
  • \$\begingroup\$ Sorry, my mistake. \$\endgroup\$
    – Jakube
    Commented Sep 18, 2017 at 20:42
3
\$\begingroup\$

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
\$\endgroup\$
3
  • \$\begingroup\$ Any reason we can't do away with the boxes? What about: [:+/-@[[\]? \$\endgroup\$
    – Jonah
    Commented Sep 19, 2017 at 0:16
  • \$\begingroup\$ @Jonah If the chunk size is larger than the length of the input array, it won't be zero-padded. \$\endgroup\$
    – miles
    Commented Sep 19, 2017 at 0:42
  • \$\begingroup\$ Nice edit -- much cleaner now. \$\endgroup\$
    – Jonah
    Commented Sep 19, 2017 at 5:42
3
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ 57 bytes \$\endgroup\$ Commented Sep 19, 2017 at 9:15
  • \$\begingroup\$ @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. \$\endgroup\$
    – Giuseppe
    Commented Sep 19, 2017 at 13:07
3
\$\begingroup\$

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

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
\$\endgroup\$
4
  • \$\begingroup\$ Almost identical to my own solution: codegolf.stackexchange.com/a/143186/73296 \$\endgroup\$
    – scottinet
    Commented Sep 19, 2017 at 13:31
  • \$\begingroup\$ @scottinet I must have missed that. They are different enough that I'll leave mine and upvote yours :) \$\endgroup\$
    – Riley
    Commented Sep 19, 2017 at 14:23
  • \$\begingroup\$ I don't really mind, just wanted to point that out :) \$\endgroup\$
    – scottinet
    Commented Sep 19, 2017 at 14:25
  • \$\begingroup\$ @scottinet It is interesting that you can rearrange the operations and come out with the same byte count and almost identical bytes used (¹ vs ²) \$\endgroup\$
    – Riley
    Commented Sep 19, 2017 at 14:30
3
\$\begingroup\$

Vyxal, 7 bytes

ẇR∆ZR∩Ṡ

Try it Online!

\$\endgroup\$
2
  • \$\begingroup\$ afaict the zfilling is unecessary as the missing zeroes are simply ignored \$\endgroup\$
    – emanresu A
    Commented May 22, 2022 at 1:08
  • 1
    \$\begingroup\$ @emanresuA that would fail on case [1,2], 3 => [1,2,0]. \$\endgroup\$
    – naffetS
    Commented May 22, 2022 at 1:09
2
\$\begingroup\$

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
\$\endgroup\$
2
  • \$\begingroup\$ What's the F for in the Try it Here code you linked? \$\endgroup\$
    – Pavel
    Commented Sep 18, 2017 at 19:47
  • \$\begingroup\$ @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. \$\endgroup\$
    – dzaima
    Commented Sep 18, 2017 at 19:48
2
\$\begingroup\$

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

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

Mathematica, 43 bytes

Plus@@#~ArrayReshape~{⌈Tr[1^#]/#2⌉,#2}&
\$\endgroup\$
2
\$\begingroup\$

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], [4]]
    (:`R0)   -- ... prepend [0,...,0] (length n)         | [[0,0,0], [1,2,3], [4]]
F            -- accumulate the sublists with             |
 ż+          -- element-wise addition                    | [0+1+4, 0+2, 0+3]
\$\endgroup\$
2
\$\begingroup\$

Clojure, 42 bytes

#(apply map +(partition %2 %2(repeat 0)%))

Try it online!

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

Jq 1.5, 31 bytes

[_nwise($n)]|transpose|map(add)

Sample Run

$ jq -Mc --argjson n 3 '[_nwise($n)]|transpose|map(add)' <<< "[1,2,3,4,5,6,7,8]"
[12,15,9]

Takes advantage of builtins: _nwise, transpose, add and map

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

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

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!

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

Japt, 7 bytes

Man, I fought with the wrong Japt method for far too long trying to get it to work for the [1], 3 test case in a reasonable amount of bytes!

VÆëVX x

Try it


Explanation

Implicit input of array U and integer 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.

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

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[8] = {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).

\$\endgroup\$
1

Your Answer

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

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