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

# 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 – Wheat Wizard 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

Try it online!