# 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, 2019 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, 2019 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. Mar 6, 2019 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, 2019 at 23:44
• What if the input array contains a 0? Mar 7, 2019 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: ι Mar 7, 2019 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 :/ Mar 7, 2019 at 9:06
• So there is a language with a built-in for this! :D Mar 7, 2019 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.

# Wolfram Language (Mathematica), 28 bytes

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

Try it online!

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

# Japt, 2 bytes

Takes the array as the first input.

óV

Try it

# Jelly, 6 2 bytes

sZ

Try it online!

Thanks to @JonathanAllan for saving 4 bytes

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

# Python 2, 37 bytes

### Code:

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

Try it online!

# Haskell, 39 bytes

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. Mar 7, 2019 at 0:40
• chunksOf only seems to appear with the signature Int -> Text -> [Text].1 Mar 7, 2019 at 0:47
• @JosephSible, it's in the lists package. Mar 7, 2019 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. Mar 7, 2019 at 0:50

# 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! Mar 7, 2019 at 1:21

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

# Wolfram Language (Mathematica), 25 bytes

#2[[i;;;;#]]~Table~{i,#}&

Try it online!

• O_o explanation pls May 15, 2019 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, 2019 at 3:23
• oh yeah, forgot it was ;; not ; lol. was looking at this going "wth is i ; ; ; ; #" May 15, 2019 at 3:51

# 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?" Mar 8, 2019 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. Mar 8, 2019 at 8:21

# 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!

# 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? Mar 8, 2019 at 18:05
• @JonathanFrech There you go. Mar 22, 2019 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 May 14, 2019 at 20:19

# 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

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

• And here, I golfed it down to 90 bytes. Mar 8, 2019 at 8:49
• @OlivierGrégoire thanks! Somewhat new to this and was working on the lambda bit but struggling. Mar 8, 2019 at 13:58

Try it online!

# 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. Mar 6, 2019 at 23:20
• It's generally discouraged to post solutions to your own challenges immediately. Mar 6, 2019 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. Mar 6, 2019 at 23:25
• @Joe king you are right! I made a typo :/ Mar 6, 2019 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.

• I think we all agree for the sandbox Mar 21, 2019 at 8:13