Created
July 8, 2010 22:43
-
-
Save dlundquist/468757 to your computer and use it in GitHub Desktop.
Faro Shuffle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/ruby | |
MAX_ROUNDS = 50 | |
# Splits the deck of cards into two equal parts | |
# in the case of an odd deck size, the extra card goes in the first part | |
def cut(cards) | |
b_size = cards.length / 2 | |
a_size = cards.length - b_size | |
a = cards[0..(a_size-1)] | |
b = cards[(a_size)..(cards.length - 1)] | |
raise("a wrong length") unless a.length == a_size | |
raise("b wrong length") unless b.length == b_size | |
raise("did not cut deck evenly") unless a.length == b.length or a.length == b.length + 1 | |
return a, b | |
end | |
def shuffle(a, b) | |
result = Array.new | |
while a.any? and b.any? | |
result.push(a.shift) | |
result.push(b.shift) | |
end | |
# Handle the odd deck size case | |
result.push(a.shift) if a.length == 1 | |
raise("a not empty") unless a.empty? | |
raise("b not empty") unless b.empty? | |
return result | |
end | |
puts "Deck\tFaro Shuffles" if ARGV.include?('-d') | |
(1..1000).each do |deck_size| | |
deck = (1..deck_size).to_a | |
original = deck.dup | |
count = 0 | |
begin | |
begin | |
deck = shuffle(*cut(deck)) | |
count += 1 | |
raise("reached max rounds") if count >= MAX_ROUNDS | |
end while (deck != original) | |
if ARGV.include?('-d') | |
puts "#{deck_size}\t#{count}" | |
else | |
puts "A #{deck_size} card deck reaches the original order after #{count} perfect faro shuffles." | |
end | |
rescue Exception => e | |
puts "A #{deck_size} card deck caused an exception: #{e}" unless ARGV.include?('-d') | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment