Created
December 18, 2011 14:28
-
-
Save techbelly/1493576 to your computer and use it in GitHub Desktop.
Biased 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
def swap(array,indexa,indexb) | |
value_to_swap = array[indexa] | |
array[indexa] = array[indexb] | |
array[indexb] = value_to_swap | |
end | |
def biased_shuffle(array) | |
array = array.dup | |
array.size.times do |i| | |
swap(array,rand(array.size),i) | |
end | |
array | |
end | |
def fair_shuffle(array) | |
array = array.dup | |
array.length.downto(1) do |i| | |
swap(array,rand(i),i-1) | |
end | |
array | |
end | |
def montecarlo(source,samples=60000) | |
results = Hash.new(0) | |
samples.times do | |
sample = yield source | |
key = sample.join("") | |
results[key] = results[key] + 1 | |
end | |
results | |
end | |
biased = montecarlo(["a","b","c"]) do |y| | |
biased_shuffle y | |
end | |
fair = montecarlo(["a","b","c"]) do |y| | |
fair_shuffle y | |
end | |
puts "BIASED SHUFFLE RESULTS" | |
puts biased.inspect | |
puts | |
puts "FAIR SHUFFLE RESULTS" | |
puts fair.inspect | |
puts | |
# BIASED SHUFFLE RESULTS | |
# {"acb"=>11104, "bca"=>11225, "cba"=>8947, "abc"=>8874, "cab"=>8832, "bac"=>11018} | |
# FAIR SHUFFLE RESULTS | |
# {"acb"=>9829, "bca"=>10206, "cba"=>9888, "abc"=>10065, "cab"=>9970, "bac"=>10042} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment