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 withA
as it's only elementIf
n
is greater than the length ofA
, you will need to return every hand and an empty hand. ifn = 4
andarray 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
andA= [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)
This is code-golf, so you the shortest bytes of each language will be the winner.
Inspired from Create chunks from array by chau giang
0
? \$\endgroup\$