22
\$\begingroup\$

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],[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 , so you the shortest bytes of each language will be the winner.

\$\endgroup\$
12
  • 5
    \$\begingroup\$ If n is greater than the length of A we need to return A‽ Are you sure you don't mean [A]? \$\endgroup\$
    – Adám
    Mar 6, 2019 at 13:24
  • 10
    \$\begingroup\$ @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? \$\endgroup\$
    – Adám
    Mar 6, 2019 at 13:42
  • 5
    \$\begingroup\$ @chaugiang Adam is correct imo. The return value should be consistent. \$\endgroup\$
    – Jonah
    Mar 6, 2019 at 16:02
  • 1
    \$\begingroup\$ @chaugiang Can n ever equal 1? \$\endgroup\$
    – DJMcMayhem
    Mar 6, 2019 at 19:41
  • 6
    \$\begingroup\$ In a strongly typed language, it's simply impossible to return A rather than [A] , which would exclude an awful lot of languages. \$\endgroup\$
    – dfeuer
    Mar 6, 2019 at 22:48

43 Answers 43

15
\$\begingroup\$

05AB1E, 1 byte

ô

Try it online or verify all test cases.

Builtins ftw. :)

\$\endgroup\$
9
\$\begingroup\$

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)
\$\endgroup\$
1
  • \$\begingroup\$ Now that is a neat and clean solution, and I learned about recursive anonymous functions too! \$\endgroup\$ Mar 7, 2019 at 17:44
9
\$\begingroup\$

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!

\$\endgroup\$
1
  • 7
    \$\begingroup\$ Congratulations on your first APL answer. And nicely explained too! Here, have an APL pie: 🥧 \$\endgroup\$
    – Adám
    Mar 6, 2019 at 13:08
9
\$\begingroup\$

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.

\$\endgroup\$
0
8
\$\begingroup\$

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

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

Try it online!.

\$\endgroup\$
6
\$\begingroup\$

PHP, 15 bytes

$f=array_chunk;

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

\$\endgroup\$
2
  • 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
    Mar 6, 2019 at 16:12
  • \$\begingroup\$ @Neil I thought that might be a forbidden loophole; but you may be right. \$\endgroup\$
    – Titus
    Mar 8, 2019 at 15:22
6
\$\begingroup\$

Perl 6, 13 bytes

{*.batch($_)}

Try it online!

Curried function wrapping the batch built-in.

\$\endgroup\$
2
  • \$\begingroup\$ Did they fix that bug where you had to have a ; after the Whatever code? \$\endgroup\$
    – Jo King
    Mar 6, 2019 at 22:44
  • 2
    \$\begingroup\$ @JoKing No. You only need a ; when passing arguments with $^a or @_. \$\endgroup\$
    – nwellnhof
    Mar 7, 2019 at 1:18
5
\$\begingroup\$

Clean, 54 bytes

import StdEnv
$n l=[l%(i,i+n-1)\\i<-[0,n..length l-1]]

Try it online!

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

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.

\$\endgroup\$
2
  • 4
    \$\begingroup\$ 36 bytes as a recursive lambda function \$\endgroup\$
    – ovs
    Mar 6, 2019 at 14:45
  • \$\begingroup\$ @ovs - Very nice and also different enough for you to post as your own answer if you wish. \$\endgroup\$
    – ElPedro
    Mar 6, 2019 at 14:55
5
\$\begingroup\$

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
\$\endgroup\$
7
  • 2
    \$\begingroup\$ Remove the spaces for 71 characters \$\endgroup\$
    – MilkyWay90
    Mar 7, 2019 at 1:31
  • \$\begingroup\$ lol, I thought I removed all of them but I didn't notice those, thanks! \$\endgroup\$
    – vityavv
    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
    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\$
    – vityavv
    Mar 8, 2019 at 1:01
  • \$\begingroup\$ Could A space n n n ... work (or space A n n n...)? \$\endgroup\$
    – MilkyWay90
    Mar 8, 2019 at 2:50
5
\$\begingroup\$

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!

\$\endgroup\$
1
4
\$\begingroup\$

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!

\$\endgroup\$
4
\$\begingroup\$

Brachylog, 2 bytes

ġ₎

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ I read the statement, This came to mind immediately =). #builtinsFTW \$\endgroup\$
    – Kroppeb
    Mar 9, 2019 at 17:13
4
\$\begingroup\$

Elixir, 16 bytes

Enum.chunk_every

Try it online!

\$\endgroup\$
4
\$\begingroup\$

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

C# (Visual C# Interactive Compiler), 78 77 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'.

\$\endgroup\$
4
\$\begingroup\$

F# (.NET Core), 15 bytes

Seq.chunkBySize

Try it online!

Well F# has a builtin...

\$\endgroup\$
4
\$\begingroup\$

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.

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

Japt, 2 bytes

òV

Try it online!

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

PHP, 45 bytes

function f($a,$b){return array_chunk($a,$b);}

Try it online!

\$\endgroup\$
4
  • 3
    \$\begingroup\$ Would just array_chunk be a valid answer? \$\endgroup\$
    – Arnauld
    Mar 6, 2019 at 12:19
  • \$\begingroup\$ @Arnauld I dont know. Never golfed in php before although I use it at work. \$\endgroup\$ 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
    Mar 6, 2019 at 12:30
  • \$\begingroup\$ (erratum: I meant undefined constants) \$\endgroup\$
    – Arnauld
    Mar 6, 2019 at 12:38
3
\$\begingroup\$

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

K (oK), 10 bytes

{(0N,x)#y}

Try it online!

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

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!

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

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!

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

Coconut, 8 bytes

groupsof

Try it online!

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

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

Clojure, 14 bytes

#(partition %)

builtins I guess

\$\endgroup\$
1
  • \$\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
    Mar 7, 2019 at 17:05
3
\$\begingroup\$

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!

\$\endgroup\$
2
  • \$\begingroup\$ I think you can \$\endgroup\$
    – aloisdg
    Mar 6, 2019 at 22:27
  • 1
    \$\begingroup\$ n!x=take n x:n!drop n x. Data.Lists provides also chunksOf. \$\endgroup\$
    – nimi
    Mar 6, 2019 at 23:00
3
\$\begingroup\$

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!

\$\endgroup\$
1
  • 2
    \$\begingroup\$ You should be able to rv b (alias for Remove-Variable) instead of $b=@() to save two bytes. \$\endgroup\$ Mar 6, 2019 at 20:45
3
\$\begingroup\$

R, 49 36 bytes

function(A,n)split(A,(seq(A)-1)%/%n)

Try it online!

Thanks to Kirill L. for the golf.

\$\endgroup\$
2
  • \$\begingroup\$ How about this, for 36 \$\endgroup\$
    – Kirill L.
    Mar 7, 2019 at 8:27
  • \$\begingroup\$ @KirillL. of course. Thanks! \$\endgroup\$
    – Giuseppe
    Mar 7, 2019 at 14:08

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.