Skip to content

Instantly share code, notes, and snippets.

@kinduff
Created April 2, 2015 18:55
Show Gist options
  • Save kinduff/7b2c8a809c1e94872226 to your computer and use it in GitHub Desktop.
Save kinduff/7b2c8a809c1e94872226 to your computer and use it in GitHub Desktop.
Mathematical Magic Trick
# 52-Card Perfect Shuffles - Numberphile
# https://www.youtube.com/watch?v=Y2lXsxmBx7E
module Magic
class Sys
class << self
def ask
print "I choose: "
gets.chomp
end
def picks
[*'A'..'Z'].each_with_index.map{|l,i| l+i.to_s }
end
def shuffle array, type
new_array = []
half = array.length/2
sliced = array.each_slice(half).to_a
f_half = sliced.first
l_half = sliced.last
half.times do
shuffled_pair = [f_half.shift, l_half.shift]
shuffled_pair = shuffled_pair.reverse if type == 1
new_array << shuffled_pair
end
new_array.flatten
end
end
end
class Trick
class << self
def start
original_picks = Sys.picks
puts "Pick one:"
puts original_picks.join(', ')
number_pick = ask_for_pick original_picks
puts "Random shuffle'"
shuffle_picks = original_picks.shuffle
puts shuffle_picks.join(', ')
puts "Move #{number_pick} to the front"
picks = shuffle_picks.unshift shuffle_picks.delete_at(shuffle_picks.index(number_pick))
puts picks.join(', ')
puts "Choose a number between 1 and #{picks.count}"
number = ask_for_number picks.count
binary = (number-1).to_s(2)
shuffle_times = binary.split('').map(&:to_i)
puts "I'll make #{shuffle_times.count} perfect shuffles"
shuffle_times.each_with_index do |type, index|
picks = Sys.shuffle picks, type
puts "Perfect shuffle #{index+1}"
puts picks.join(', ')
end
puts "Pick #{number_pick} should be on position #{number}."
puts "Pick #{number_pick} is in position #{picks.index(number_pick)+1}."
end
private
def ask_for_pick picks
number_pick = Sys.ask
unless picks.include?(number_pick)
puts "Not valid, try again."
ask_for_pick picks
end
number_pick
end
def ask_for_number picks
number = Sys.ask.to_i
unless number.between?(1, picks)
puts "Not valid, try again."
ask_for_number picks
end
number
end
end
end
end
Magic::Trick.start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment