Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to enumerate permutations of deck of cards?

I'm looking to make a function that would assign a value to a specific shuffle of cards.

The function has to be bijective. The deck has 52 cards so there are 52! different shuffles, therefore the domain is the set of all permutations of 52 cards, and the codomain is integers from 1 to 52!.

What would be the best algorithm to do this fast and efficiently?

like image 414
Davo Avatar asked Jan 05 '18 12:01

Davo


People also ask

How many possible permutations are there in a deck of cards?

It seems unbelievable, but there are somewhere in the range of 8x1067 ways to sort a deck of cards. That's an 8 followed by 67 zeros.

How many ways can a 52 card deck be arranged?

The number of possible ways to order a pack of 52 cards is '52! ' (“52 factorial”) which means multiplying 52 by 51 by 50… all the way down to 1. The number you get at the end is 8×10^67 (8 with 67 '0's after it), essentially meaning that a randomly shuffled deck has never been seen before and will never be seen again.

How do you organize a deck of cards?

Give a Master Deck of cards arranged in an easy to recognize order (such as ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, and King in Clubs, Hearts, Spades, and Diamonds). Give a shuffled deck and ask the group to rearrange the cards in the same order as the Master Deck.

How many combinations of 3 playing cards from a 52 card deck exist?

To answer a), we note that there 52 ways to choose the first card, 51 ways to choose the second card, and 50 ways to choose the third card, for a total of 52*51*50=132,600 ways.


1 Answers

To encode a permutation to a value in pseudocode:

A = list of cards
value = 0
for i in range(52):
   cards_left = 52-i
   let pos = index of card i in A 
   delete A[pos]
   value = value * cards_left + pos

At the end, A will be an empty list, and value has a number representing the permutation.

To decode:

A = []
value is an input
for i in reversed(range(52)):
   cards_left = 52-i
   pos = value % cards_left
   value = value / cards_left
   Insert card i at index pos in A

At end, A should contain the original permutation.

Example Python code:

B=[3,2,0,1,4]

def encode(A):
    value = 0
    n = len(A)
    A = A[:] # Take a copy to avoid modifying original input array 
    for i in range(n):
       cards_left = n-i
       pos = A.index(i)
       del A[pos]
       value = value * cards_left + pos
    return value

def decode(value,n):
    A=[]
    for i in range(n-1,-1,-1):
       cards_left = n-i
       value,pos = divmod(value, cards_left)
       A.insert(pos,i)
    return A

v=encode(B)
print v
print decode(v,len(B))
like image 84
Peter de Rivaz Avatar answered Sep 20 '22 11:09

Peter de Rivaz