Create chunks from an array

Your task is to write a program which given an array and a number, you need to split the array into chunks with size is number.

Rules

Your program will receive an array A , as well as a positive integer n. The array should then be split into chunks of length n, if the length of the string isn't divisible by n any leftover at the end should be considered its own chunk.

• If n is greater than length of array A, you will need to return array A, for example: if n = 4 and array A = [1,2,3], you should return [1,2,3]

• The array can contain any type rather than number.

• You should not change order (or direction) of any item from left to right. For example if n = 2 and A= [1,2,3]. Any result rather than [[1,2],] will be invalid.

Test Cases

n   A               Output

2   [1,2,3,4,5,6]   [[1,2],[3,4],[5,6]]
3   [1,2,3,4,5,6]   [[1,2,3],[4,5,6]]
4   [1,2,3,4,5,6]   [[1,2,3,4],[5,6]]

This is , so you the shortest bytes of each language will be the winner.

• If n is greater than the length of A we need to return A‽ Are you sure you don't mean [A]? – Adám Mar 6 at 13:24
• @chaugiang I still think a too large n should return [A], e.g [[1,2,3]]. What if n is exactly the length of A? – Adám Mar 6 at 13:42
• @chaugiang Adam is correct imo. The return value should be consistent. – Jonah Mar 6 at 16:02
• @chaugiang Can n ever equal 1? – DJMcMayhem Mar 6 at 19:41
• In a strongly typed language, it's simply impossible to return A rather than [A] , which would exclude an awful lot of languages. – dfeuer Mar 6 at 22:48

ô

Builtins ftw. :)

JavaScript (ES6), 36 bytes

Takes input as (n)(array).

n=>g=a=>a+a&&[a.splice(0,n),...g(a)]

Try it online!

Commented

n =>                  // n = chunk size
g = a =>            // g = recursive function taking the array a[]
a + a             // if a[] is empty, stop recursion and return an empty string
&&                // otherwise, return an array made of:
[ a.splice(0, n), //   the next chunk
...g(a)         //   followed by the result of a recursive call
]                 //   (the last call leads to ...'', which adds nothing)
• Now that is a neat and clean solution, and I learned about recursive anonymous functions too! – Joe the Person Mar 7 at 17:44

APL (Dyalog Unicode), 12 bytesSBCS

⊢⊂⍨(⍴⊢)⍴1↑⍨⊣

Big thanks to Adám for basically doing basically all the golfing (and for basically all the APL knowledge I have currently >_>).

Explanation

⊂⍨           Partitioned enclose (commuted, i.e. left and right switched) - for each ⍵ in left, ⍺ in right, if ⍺ = 0, create a new sub-array, push ⍵ to latest sub-array
⊢             Right argument of entire expression
⍴      Reshape - Change size of right into dimensions specified by left
(⍴ )       Shape of (here, there is only one dimension - length)
⊢        Right argument of entire expression
↑⍨   Take (commuted) - takes ⍺ elements from left where ⍺ is right. Extra elements (zeroes here) are automatically added
1     1
⊣  Left argument of entire expression

Execution

Arguments 2, 1 2 3 4 5 6 7. Note that APL arrays are of the form a b c, with optional surrounding parentheses.

⊣  2
1     1
↑⍨   1↑2 = 1 0
⊢        1 2 3 4 5 6 7
(⍴ )       ⍴1 2 3 4 5 6 7 = 7
⍴      7⍴1 0 = 1 0 1 0 1 0 1
⊢             1 2 3 4 5 6 7
⊂⍨           1 0 1 0 1 0 1⊂1 2 3 4 5 6 7 = (1 2)(3 4)(5 6)(7)

Try it online!

• Congratulations on your first APL answer. And nicely explained too! Here, have an APL pie: 🥧 – Adám Mar 6 at 13:08

Python 3, 61 bytes

lambda A,n:[A,[A[x:x+n]for x in range(0,len(A),n)]][n<len(A)]

Try it online!

Modifies Henry T's existing Python 3 solution to produce valid output for n >= len(A).
Posting as its own answer due to lack of commenting privileges.

Prolog (SWI), 9084 61 bytes

Code:

[]*_*[].
L*N*[P|R]:-length(P,N),append(P,T,L),T*N*R;P=L,R=[].

The input format might be a bit weird, but it is:

A * n * Result.

For example, for the input:

n = 2
A = [1, 2, 3, 4, 5, 6]

You would need to use [1, 2, 3, 4, 5, 6] * 2 * Result..

Try it online!

Ungolfed version:

divide([], _, []).
divide(List, N, [Prefix | Result]) :-
length(Prefix, N), append(Prefix, Remaining, List), divide(Remaining, N, Result)
; Prefix = List, Result = [].

PHP, 15 bytes

$f=array_chunk; requires PHP 7. Call with$f(ARRAY, N).

• I don't think you're required to give another name to a builtin, so this just scores 11, doesn't it? – Neil Mar 6 at 16:12
• @Neil I thought that might be a forbidden loophole; but you may be right. – Titus Mar 8 at 15:22

Perl 6, 13 bytes

{*.batch($_)} Try it online! Curried function wrapping the batch built-in. • Did they fix that bug where you had to have a ; after the Whatever code? – Jo King Mar 6 at 22:44 • @JoKing No. You only need a ; when passing arguments with$^a or @_. – nwellnhof Mar 7 at 1:18

Clean, 54 bytes

import StdEnv
$n l=[l%(i,i+n-1)\\i<-[0,n..length l-1]] Try it online! Python 2, 39 bytes i,j=input() while j:print j[:i];j=j[i:] Try it online! Assumes that 1 chunk per line is acceptable output. • 36 bytes as a recursive lambda function – ovs Mar 6 at 14:45 • @ovs - Very nice and also different enough for you to post as your own answer if you wish. – ElPedro Mar 6 at 14:55 Brainfuck, 71 bytes ,[>+>+<<-]>>>,[<[>.,<-]>>>++++[<++++++++>-]<.[-]<<<[<+>>+<-]<[->+<]>>>] Dunno if this counts or not... input format: <character whose ascii is n>AAAAAAAAAAAAA For example, in the input: 1234567890123492034 n is 32 since the ASCII value of space is 32 Takes the input and puts in a space every time n characters pass Explanation (no commas because that would break the program): , take n [>+>+<<-] copy into next two cells (destroys original) >>>, take first of A into next cell [ while that input exists <[>.,<-] if n is nonzero output take next of A subtract one from n >>>++++[<++++++++>-]<.[-]< n is zero so put a space <<[<+>>+<-] copy the old n into surrounding cells <[->+<] move from first cell to second >>>] take input, do again • Remove the spaces for 71 characters – MilkyWay90 Mar 7 at 1:31 • lol, I thought I removed all of them but I didn't notice those, thanks! – vityavv Mar 7 at 1:45 • Try reorganizing the cells such that the cells you use more are more accessible (for example, if the input cell (the one where you use , more) is used more it could be put an a cell which is easier to access than if it was placed in other cells) or use a bruteforcer. I am not skilled in golfing in BF so these suggestions may not be helpful. – MilkyWay90 Mar 7 at 3:06 • So far I have n n n A space as my cell setup, if you can think of a better way... – vityavv Mar 8 at 1:01 • Could A space n n n ... work (or space A n n n...)? – MilkyWay90 Mar 8 at 2:50 Python 3, 46 chars lambda A,n:[A[:n],*(f(A[n:],n)if A[n:]else[])] -1 thanks to @Collin Phillips. Try it online! CJam, 3 bytes {/} This is an anonymous block that takes an array of numbers and a number from the stack, and replaces them by an array of arrays. Try it online! Brachylog, 2 bytes ġ₎ Try it online! • I read the statement, This came to mind immediately =). #builtinsFTW – Kroppeb Mar 9 at 17:13 Elixir, 16 bytes Enum.chunk_every Try it online! Charcoal, 1 byte Try it online! Charcoal's default I/O makes it difficult to demonstrate using anything except strings. If you want a full program that takes numeric lists and outputs formatted lists then this can be done as follows: Ｅ⪪ＡＮ⪫ι, Try it online! Link is to verbose version of code. Explanation: Ａ Input array ⪪ Split into chunks of Ｎ Input number Ｅ Map over chunks ι Current chunk ⪫ Joined with , Literal , Implicitly print each chunk on its own line C# (Visual C# Interactive Compiler), 7877 43 bytes a=>b=>{int i=0;return a.GroupBy(_=>i++/b);} Try it online! I think we should be able to just write int i; because 0 is the default of int. I let it to avoid the error: error CS0165: Use of unassigned local variable 'i'. F# (.NET Core), 15 bytes Seq.chunkBySize Try it online! Well F# has a builtin... J, 4 bytes <\~- Try it online! Takes the array as left arg and chunk size as right arg. Uses a dyadic hook and the infix adverb with a negative argument, which does what we want by definition. Note: The return type must be boxed because J only allows tables of equal sized items. Japt, 2 bytes òV Try it online! PHP, 45 bytes function f($a,$b){return array_chunk($a,$b);} Try it online! • Would just array_chunk be a valid answer? – Arnauld Mar 6 at 12:19 • @Arnauld I dont know. Never golfed in php before although I use it at work. – Luis felipe De jesus Munoz Mar 6 at 12:21 • I'm not 100% sure either, but we can abuse the implicit conversion of undeclared variables to a string and do something like that. – Arnauld Mar 6 at 12:30 • (erratum: I meant undefined constants) – Arnauld Mar 6 at 12:38 Java 10, 106 80 bytes L->n->{for(int l=L.size(),i=0;i<l;)System.out.print(L.subList(i,(i+=n)<l?i:l));} Prints the chunks without delimiter. Try it online. 106 bytes: L->n->{var r=new java.util.Stack();for(int l=L.size(),i=0;i<l;)r.add(L.subList(i,(i+=n)<l?i:l));return r;} Actually returns a list of lists. Try it online. Explanation: L->n->{ // Method with List and integer parameters and List return-type var r=new java.util.Stack();// Create an empty List for(int l=L.size(), // Determine the size of the input-List i=0;i<l;) // Loop i in the range [0, size): r.add( // Add to the result-List: L.subList(i, // A sublist of the input-list in the range from i Math.min(i+=n,l))); // to the minimum of: i + input-integer or the size // (and increase i by the input-integer at the same) return r;} // Return the List of Lists of integers as result K (oK), 10 bytes {(0N,x)#y} Try it online! Ruby, 25 bytes ->n,a{[*a.each_slice(n)]} Try it online! If we can return enumerators instead of arrays, then it becomes simply: Ruby, 21 bytes ->n,a{a.each_slice n} Try it online! PicoLisp, 75 74 bytes (de f(n l)(if(>= n(length l))(list l)(cons(head n l)(f n(tail(- 0 n)l))))) Try it online! Coconut, 8 bytes groupsof Try it online! V, 6 bytes òÀf,r Try it online! Hexdump: 00000000: f2c0 662c 720a ..f,r. Explanation: ò " Until an error happens: f " (f)ind the... À " n'th... , " "," " (If there are less than n commas after the cursor, throw an error) r " Replace the char under the cursor with... <cr> " A newline Clojure, 14 bytes #(partition %) builtins I guess • Hi, welcome. The function should take two arguments: the array to be partitioned and the length of the chunk. Also what happens if the last chunk isn't "full" when using partition? – NikoNyrh Mar 7 at 17:05 Haskell, 26 bytes import Data.Lists chunksOf Here's a more interesting version, with just a few more bytes (thanks to nimi for five bytes in each solution): Haskell, 31 bytes n![]=[] n!x=take n x:n!drop n x Try it online! • I think you can – aloisdg Mar 6 at 22:27 • n!x=take n x:n!drop n x. Data.Lists provides also chunksOf. – nimi Mar 6 at 23:00 PowerShell, 67 65 bytes -2 bytes thanks AdmBorkBork param($n,$a)$a|%{$b+=,$_
if($b.Count-ge$n){,$b;rv b}} if($b){,$b} Try it online! • You should be able to rv b (alias for Remove-Variable) instead of$b=@() to save two bytes. – AdmBorkBork Mar 6 at 20:45

Jelly, 1 byte

s

Try it online!

While the printer makes it look like single-element splits are not wrapped into lists, they actually are.

• This night give a better output as to showing that single element arrays are still actually arrays. – Nick Kennedy Mar 6 at 13:33
• Er, is the downvote because I didn’t add @Nick Kennedy’s link? – Ven Mar 7 at 7:48
• certainly not from me – Nick Kennedy Mar 7 at 7:49