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 arrayA
, you will need to return arrayA
, for example: ifn = 4
andarray 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
andA= [1,2,3]
. Any result rather than[[1,2],[3]]
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 code-golf, so you the shortest bytes of each language will be the winner.
43 Answers 43
JavaScript (ES6), 36 bytes
Takes input as (n)(array)
.
n=>g=a=>a+a&&[a.splice(0,n),...g(a)]
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)
-
\$\begingroup\$ Now that is a neat and clean solution, and I learned about recursive anonymous functions too! \$\endgroup\$Joe the Person– Joe the Person2019年03月07日 17:44:13 +00:00Commented Mar 7, 2019 at 17:44
APL (Dyalog Unicode), 12 bytes SBCS
⊢⊂⍨(⍴⊢)⍴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)
-
7\$\begingroup\$ Congratulations on your first APL answer. And nicely explained too! Here, have an APL pie: 🥧 \$\endgroup\$Adám– Adám2019年03月06日 13:08:05 +00:00Commented Mar 6, 2019 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)]
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), (削除) 90 (削除ここまで) (削除) 84 (削除ここまで) 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.
.
Ungolfed version:
divide([], _, []).
divide(List, N, [Prefix | Result]) :-
length(Prefix, N), append(Prefix, Remaining, List), divide(Remaining, N, Result)
; Prefix = List, Result = [].
-
\$\begingroup\$ Did they fix that bug where you had to have a
;
after the Whatever code? \$\endgroup\$Jo King– Jo King2019年03月06日 22:44:47 +00:00Commented Mar 6, 2019 at 22:44 -
2\$\begingroup\$ @JoKing No. You only need a
;
when passing arguments with$^a
or@_
. \$\endgroup\$nwellnhof– nwellnhof2019年03月07日 01:18:50 +00:00Commented Mar 7, 2019 at 1:18
PHP, 15 bytes
$f=array_chunk;
requires PHP 7. Call with $f(ARRAY, N)
.
-
6\$\begingroup\$ I don't think you're required to give another name to a builtin, so this just scores 11, doesn't it? \$\endgroup\$Neil– Neil2019年03月06日 16:12:46 +00:00Commented Mar 6, 2019 at 16:12
-
\$\begingroup\$ @Neil I thought that might be a forbidden loophole; but you may be right. \$\endgroup\$Titus– Titus2019年03月08日 15:22:53 +00:00Commented Mar 8, 2019 at 15:22
Python 2, 39 bytes
i,j=input()
while j:print j[:i];j=j[i:]
Assumes that 1 chunk per line is acceptable output.
-
4
-
\$\begingroup\$ @ovs - Very nice and also different enough for you to post as your own answer if you wish. \$\endgroup\$ElPedro– ElPedro2019年03月06日 14:55:03 +00:00Commented Mar 6, 2019 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
-
2\$\begingroup\$ Remove the spaces for 71 characters \$\endgroup\$MilkyWay90– MilkyWay902019年03月07日 01:31:09 +00:00Commented Mar 7, 2019 at 1:31
-
\$\begingroup\$ lol, I thought I removed all of them but I didn't notice those, thanks! \$\endgroup\$willowis.cool– willowis.cool2019年03月07日 01:45:35 +00:00Commented Mar 7, 2019 at 1:45
-
\$\begingroup\$ 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. \$\endgroup\$MilkyWay90– MilkyWay902019年03月07日 03:06:32 +00:00Commented Mar 7, 2019 at 3:06 -
\$\begingroup\$ So far I have
n n n A space
as my cell setup, if you can think of a better way... \$\endgroup\$willowis.cool– willowis.cool2019年03月08日 01:01:46 +00:00Commented Mar 8, 2019 at 1:01 -
\$\begingroup\$ Could
A space n n n ...
work (orspace A n n n...
)? \$\endgroup\$MilkyWay90– MilkyWay902019年03月08日 02:50:20 +00:00Commented Mar 8, 2019 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.
-
1\$\begingroup\$ I was able to get it to 46 characters with recursion \$\endgroup\$Collin Phillips– Collin Phillips2019年03月06日 21:57:47 +00:00Commented Mar 6, 2019 at 21:57
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.
-
\$\begingroup\$ I read the statement, This came to mind immediately =). #builtinsFTW \$\endgroup\$Kroppeb– Kroppeb2019年03月09日 17:13:40 +00:00Commented Mar 9, 2019 at 17:13
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:
E⪪AN⪫ι,
Try it online! Link is to verbose version of code. Explanation:
A Input array
⪪ Split into chunks of
N Input number
E Map over chunks
ι Current chunk
⪫ Joined with
, Literal `,`
Implicitly print each chunk on its own line
C# (Visual C# Interactive Compiler), (削除) 78 (削除ここまで) (削除) 77 (削除ここまで) 43 bytes
a=>b=>{int i=0;return a.GroupBy(_=>i++/b);}
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'
.
J, 4 bytes
<\~-
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.
-
3\$\begingroup\$ Would just
array_chunk
be a valid answer? \$\endgroup\$Arnauld– Arnauld2019年03月06日 12:19:50 +00:00Commented Mar 6, 2019 at 12:19 -
\$\begingroup\$ @Arnauld I dont know. Never golfed in php before although I use it at work. \$\endgroup\$Luis felipe De jesus Munoz– Luis felipe De jesus Munoz2019年03月06日 12:21:31 +00:00Commented Mar 6, 2019 at 12:21
-
\$\begingroup\$ I'm not 100% sure either, but we can abuse the implicit conversion of undeclared variables to a string and do something like that. \$\endgroup\$Arnauld– Arnauld2019年03月06日 12:30:13 +00:00Commented Mar 6, 2019 at 12:30
-
\$\begingroup\$ (erratum: I meant undefined constants) \$\endgroup\$Arnauld– Arnauld2019年03月06日 12:38:41 +00:00Commented Mar 6, 2019 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.
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.
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
PicoLisp, (削除) 75 (削除ここまで) 74 bytes
(de f(n l)(if(>= n(length l))(list l)(cons(head n l)(f n(tail(- 0 n)l)))))
V, 6 bytes
òÀf,r
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
-
\$\begingroup\$ 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? \$\endgroup\$NikoNyrh– NikoNyrh2019年03月07日 17:05:30 +00:00Commented Mar 7, 2019 at 17:05
PowerShell, (削除) 67 (削除ここまで) 65 bytes
-2 bytes thanks AdmBorkBork
param($n,$a)$a|%{$b+=,$_
if($b.Count-ge$n){,$b;rv b}}
if($b){,$b}
-
2\$\begingroup\$ You should be able to
rv b
(alias forRemove-Variable
) instead of$b=@()
to save two bytes. \$\endgroup\$AdmBorkBork– AdmBorkBork2019年03月06日 20:45:55 +00:00Commented Mar 6, 2019 at 20:45
n
is greater than the length ofA
we need to returnA
‽ Are you sure you don't mean[A]
? \$\endgroup\$n
should return[A]
, e.g[[1,2,3]]
. What ifn
is exactly the length ofA
? \$\endgroup\$A
rather than[A]
, which would exclude an awful lot of languages. \$\endgroup\$