Created
April 17, 2011 16:36
-
-
Save n8agrin/924194 to your computer and use it in GitHub Desktop.
create a naive generator that returns zero, one or two in even, random distribution
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
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
one = 0 | |
zero = 0 | |
10000.times do |i| | |
r = rand(2) | |
one += 1 if r == 1 | |
zero += 1 if r == 0 | |
end | |
puts "EXAPLE ONE, ENSURE RAND RETURNS 0 OR 1 IN EVEN DISTRIBUTION" | |
puts "zero #{zero}" | |
puts "one #{one}" | |
total = one + zero | |
puts "0 [#{((zero.to_f/total) * 100)}%] 1 [#{((one.to_f/total) * 100)}%]" | |
# (z)ero (o)ne or (t)wo | |
# Solution assumes that we can treat the sequences of two rand calls as binary notation: | |
# 00 -> 0 | |
# 10 -> 1 | |
# 01 -> 2 | |
# 11 -> 3 | |
# when we get 11 we just rerun the function again | |
def zot() | |
r = rand(2) | |
y = rand(2) | |
return zot if r == 1 && y == 1 | |
"#{r}#{y}".to_i(2) # this is ruby's way of converting a string to an int in base 2 | |
end | |
zero = 0 | |
one = 0 | |
two = 0 | |
10000.times do |i| | |
r = zot | |
one += 1 if r == 1 | |
zero += 1 if r == 0 | |
two += 1 if r == 2 | |
end | |
puts "EXAPLE TWO, ENSURE zot RETURNS 0, 1, or 2 IN EVEN DISTRIBUTION" | |
puts "zero #{zero}" | |
puts "one #{one}" | |
puts "two #{two}" | |
puts "0 [#{((zero.to_f/total) * 100)}%] 1 [#{((one.to_f/total) * 100)}%] 2 [#{((two.to_f/total) * 100)}%]" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment