# Deal the cards to the players

Tonight is card game night! You are the dealer and your task is to write a program to deal the cards to the players.

Given an array of cards and the number of players, you need to split the array of cards into a hand for each player.

## Rules

Your program will receive an non-empty array A , as well as a non-zero positive integer n. The array should then be split into n hands. If the length of the string isn't divisible by n any leftover cards at the end should be distributed as evenly as possible.

• If n==1, you will need to return an array of array with A as it's only element

• If n is greater than the length of A, you will need to return every hand and an empty hand. if n = 4 and array A = [1,2,3], you should return [[1],[2],[3]] or [[1],[2],[3],[]]. You are free to handle the empty hand with empty, undefined or null.

• The array can contain any type rather than a number.

• You should not change the order of the array while dealing. For example if n = 2 and A= [1,2,3], any result rather than [[1,3],[2]] will be invalid.

## Test Cases

n   A               Output

1   [1,2,3,4,5,6]   [[1,2,3,4,5,6]]
2   [1,2,3,4,5,6]   [[1,3,5],[2,4,6]]
3   [1,2,3,4,5,6]   [[1,4],[2,5],[3,6]]
4   [1,2,3,4,5,6]   [[1,5],[2,6],[3],[4]]
7   [1,2,3,4,5,6]   [[1],[2],[3],[4],[5],[6]] // or [[1],[2],[3],[4],[5],[6],[]]


## Demo Program

def deal(cards, n):
i = 0
players = [[] for _ in range(n)]
for card in cards:
players[i % n].append(card)
i += 1
return players

hands = deal([1,2,3,4,5,6], 2)

print(hands)


Try it online!

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

Inspired from Create chunks from array by chau giang

• you will need to return every hands and an empty hand contradicts the last test case's first result possibility. – Adám Mar 6 '19 at 23:41
• In the future I'd recommend using the Sandbox to iron out problems and gauge community feedback before posting your question to main – Jo King Mar 6 '19 at 23:42
• @JoKing I fully agree. I didnt think I would have so much edit to do. It is like pushing to prod without deploying on beta first. Thank you for the help. – aloisdg moving to codidact.com Mar 6 '19 at 23:43
• @aloisdg I can't parse your suggested alternate rule. If the idea is like people often deal to a circle, then all the players that end up with most cards are at the beginning, and players that are at the end may get no cards. – Adám Mar 6 '19 at 23:44
• What if the input array contains a 0? – Shaggy Mar 7 '19 at 9:36

# 05AB1E, 3 1 byte

Saved 2 bytes thanks to Adnan

ι


Try it online! or as a Test Suite

Explanation

ι  # uninterleave


Does exactly what the challenge asks for

• I think this should work as well: ι – Adnan Mar 7 '19 at 8:50
• @Adnan: Yeah thanks :) Only difference is the empty list for n=7, but that is an acceptable output format. I've totally missed that built-in :/ – Emigna Mar 7 '19 at 9:06
• So there is a language with a built-in for this! :D – aloisdg moving to codidact.com Mar 7 '19 at 12:17

# R, 46 25 bytes

function(A,n)split(A,1:n)


Try it online!

splits A into groups defined by 1:n, recycling 1:n until it matches length with A.

# Perl 6, 33 24 bytes

->\b{*.classify:{$++%b}}  Try it online! Anonymous curried code block that takes a number and returns a Whatever lambda that takes a list and returns a list of lists. This takes the second option when given a number larger than the length of lists, e.g. f(4)([1,2,3]) returns [[1],[2],[3]] ### Explanation: ->\b{ } # Anonymous code block that takes a number * # And returns a Whatever lambda .classify # That groups by :{$++%b}   # The index modulo the number


# Wolfram Language (Mathematica), 28 bytes

(s=#;GatherBy[#2,#~Mod~s&])&


Try it online!

• Very cleverly done! – Greg Martin Mar 7 '19 at 10:42
• "The array can contain any type rather than a number." – att May 8 '19 at 8:40

# Japt, 2 bytes

Takes the array as the first input.

óV


Try it

# Python 2, 37 bytes

### Code:

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


Try it online!

# Jelly, 6 2 bytes

sZ


Try it online!

Thanks to @JonathanAllan for saving 4 bytes

• Does sZ not work? – Jonathan Allan Mar 7 '19 at 13:24
• @JonathanAllan yes, somehow missed that. Do you want to post as separate answer or shall I edit mine? – Nick Kennedy Mar 7 '19 at 14:34
• No you're welcome to edit :) – Jonathan Allan Mar 7 '19 at 14:39

# J, 13, 11, 10, 9 bytes

(|#\)</.]


Try it online!

## how (previous explanation, fundamentally the same)

] </.~ (| #\)
</.~          NB. box results of grouping
]               NB. the right arg by...
|      NB. the remainders of dividing...
[        NB. the left arg into...
#\   NB. the length of each prefix of...
] NB. the right arg,
NB. aka, the integers 1 thru
NB. the length of the right arg


# Charcoal, 9 bytes

ＩＥθ✂ηιＬηθ


Try it online! Link is to verbose version of code. Takes input in the order [n, A] and outputs each value on its own line and each hand double-spaced from the previous. Explanation:

  θ         First input n
Ｅ          Map over implicit range
η       Second input A
✂        Sliced
ι      Starting at current index
Ｌη    Ending at length of A
θ   Taking every nth element
Ｉ           Cast to string
Implicitly print

• +1 for making the symbol of "slice" a scissors! – Jonah Mar 7 '19 at 1:21

import Data.Lists
(transpose.).chunksOf


Note: Data.Lists is from the third-party library lists, which is not on Stackage and hence will not appear on Hoogle.

• Data.Lists doesn't seem to exist. I would assume that you meant Data.List, but it doesn't contain chunksOf. – Joseph Sible-Reinstate Monica Mar 7 '19 at 0:40
• chunksOf only seems to appear with the signature Int -> Text -> [Text].1 – Ad Hoc Garf Hunter Mar 7 '19 at 0:47
• @JosephSible, it's in the lists package. – dfeuer Mar 7 '19 at 0:48
• @SriotchilismO'Zaic, lots of things don't show up in Hoogle. It's in the split package and re-exported by the lists package. There are versions of chunksOf for lists, text, sequences, and probably other things. – dfeuer Mar 7 '19 at 0:50

# Kotlin, 5351 49 bytes

{a,n->(0..n-1).map{a.slice(it..a.size-1 step n)}}


The old, incorrect solution only worked for divisors of the array length. I'm certain this can be golfed down.

Try it online!

• invalid – ASCII-only Mar 7 '19 at 4:03
• Doesn't work when n is not a divisor of the length of the list – Jo King Mar 7 '19 at 4:04
• I see, thanks. Fixing it now – Adam Mar 7 '19 at 4:08
• I believe this is fixed @ASCII-only – Adam Mar 7 '19 at 4:19
• looks like you can remove the extra pair ot parens – ASCII-only Mar 7 '19 at 4:43

# JavaScript (Node.js), 51 bytes

A=>n=>A.map((x,i)=>e[i%=n]=[...e[i]||[],x],e=[])&&e


Try it online!

# JavaScript (Node.js), 53 bytes

A=>n=>g=(i=n)=>i?[...g(--i),A.filter(_=>i--%n==0)]:[]


Try it online!

# APL+WIN 26 or 31 bytes

If individual hands can be represented as columns of a 2D matrix then 26 bytes if an array of arrays then add 5 bytes.

(l,n)⍴((l←⌈(⍴a)÷n)×n←⎕)↑a←⎕


Try it online! ourtesy of Dyalog Classic

or

⊂[1](l,n)⍴((l←⌈(⍴a)÷n)×n←⎕)↑a←⎕


Try it online! Courtesy of Dyalog Classic

Explanation:

a←⎕ prompt for array of cards

((l←⌈(⍴a)÷n)×n←⎕)↑ prompt for integer, pad a with zeros to given even hands

(l,n)⍴ create 2D matrix with each column representing each hand

⊂[1] if required convert to nested vector - APL array of arrays

# TSQL, 44 bytes

-- @       : table containing the input
-- column c: value of the card,
-- column a: position on the card in the deck
-- @n      : number of players

DECLARE @ table(a int identity(0,1), c varchar(9))
DECLARE @n int = 4

INSERT @ values('1a'),('2c'),('3e'),('4g'),('5i'),('6k')

SELECT string_agg(c,',')FROM @ GROUP BY a%@n


Try it out

• Every time I'm on this website I see something new and go "Wow that's impressive, but why?" – MindSwipe Mar 8 '19 at 7:57
• @MindSwipe I have answered a lot of questions on StackOverflow, but many of those questions are the same or almost the same - also it feels like I am working for free. The code-golf questions are different every time and I enjoy it more because I get to use methods I rarely otherwise encounter. – t-clausen.dk Mar 8 '19 at 8:21

# MathGolf, 9 bytes

\ô_í\%q╞;


Try it online!

## Explanation

\           swap top elements (pops both input onto stack)
ô          start block of length 6
_         duplicate TOS (will duplicate the list)
í        get total number of iterations of for loop (the other input)
\       swap top elements
%      modulo (picks every n:th item of the list
q     print without newline
╞    discard from left of string/array (makes the next player pick cards starting with the next in the deck)
;   discard TOS (removes some junk in the end)


# Java (JDK), 90 bytes

A->n->{var o="";for(int h=0,i;h<n;o+="\n")for(i=h++;i<A.length;i+=n)o+=" "+A[i];return o;}


Try it online!

Thanks Olivier Grégoire for the lambda and better incrementing while iterating.

# Ruby, 81 bytes

def s a,n;a.each_with_index.inject(([[]]*n).map(&:dup)){|b,(c,d)|b[d%n]<<c;b};end


Try It Online

• Could you possibly add a link to an online testing environment for ease of verification? – Jonathan Frech Mar 8 '19 at 18:05
• @JonathanFrech There you go. – Avilyn Mar 22 '19 at 17:34
• Welcome to PPCG! There's a lot of optimizations you can do for length; for example, each_with_index is pretty expensive compared to an incrementing counter, map{[]} basically does the same thing as your map(&:dup) trick, anonymous Proc, etc. that can reduce your code down to 59 bytes. Try it online! Also check out the Ruby tips page – Value Ink May 14 '19 at 20:19

function($a,$n){while($x<$n)$c[]=array_column(array_chunk($a,$n),+$x++);return$c;}  Try it online! This will not be the shortest entry, but I thought it'd be fun to try and do it using PHP array function built-ins. Result: long. Output 1 [1,2,3,4,5,6] [[1,2,3,4,5,6]] 2 [1,2,3,4,5,6] [[1,3,5],[2,4,6]] 3 [1,2,3,4,5,6] [[1,4],[2,5],[3,6]] 4 [1,2,3,4,5,6] [[1,5],[2,6],[3],[4]] 7 [1,2,3,4,5,6] [[1],[2],[3],[4],[5],[6],[]] 5 ["9C","QD","2S","4H","6D","AS","9D","TH","5C"] [["9C","AS"],["QD","9D"],["2S","TH"],["4H","5C"],["6D"]]  • Just FYI, instead of print_flat you can just do json_encode sandbox - dosn't really change the answer any, just thought I would mention it, cheers! – ArtisticPhoenix Mar 7 '19 at 20:55 • @ArtisticPhoenix well, of course! (facepalm) Thanks! :) – 640KB Mar 7 '19 at 21:02 # Wolfram Language (Mathematica), 25 bytes #2[[i;;;;#]]~Table~{i,#}&  Try it online! • O_o explanation pls – ASCII-only May 15 '19 at 1:39 • @ASCII-only ;; ;; is just a slice, roughly equivalent to python's : :; this gets slices of every $n$th element for offsets 1...n – att May 15 '19 at 3:23 • oh yeah, forgot it was ;; not ; lol. was looking at this going "wth is i ; ; ; ; #" – ASCII-only May 15 '19 at 3:51 # C# (Visual C# Interactive Compiler), 43 bytes a=>b=>{int i=0;return a.GroupBy(_=>i++%b);}  Try it online! • @JoKing [1,2,3], 4 should output [[1],[2],[3]]. You are dealing 3 cards to 4 players. I will update the main question. – aloisdg moving to codidact.com Mar 6 '19 at 23:20 • It's generally discouraged to post solutions to your own challenges immediately. – Shaggy Mar 6 '19 at 23:22 • @Shaggy ok I will take it into account for the next time. It is fine on so and rpg but I guess the competitive aspect of codegolf made it a bit unfair to self post directly. Make sense. – aloisdg moving to codidact.com Mar 6 '19 at 23:25 • @Joe king you are right! I made a typo :/ – aloisdg moving to codidact.com Mar 6 '19 at 23:26 # C (gcc), 5 bytes The compiler flag -Df= (req. leading space) fulfills specification. f(n_cards,n_hands,card_ptr) evaluates to a pointer to a list of hands. # Explanation In C, it is common practice to implement lists of lists as a single interleaved array, when the number of lists remains constant but all lists can be extended. For example, in this case of dealing cards, it is more common for more cards to get added to each hand than more hands to be added, so it would be reasonable to implement a list of hands as an interleaved list. Coincidentally, the "deck" is such a list, and thus we return the parameter unmodified. This challenge probably should've been sandboxed. # Perl 5-la, 66 56 bytes $,=<>;map{push@$_,shift@F}1..$,while@F;say"@$_"for 1..$,


Try it online!