Skip to content

Instantly share code, notes, and snippets.

@fronx
Created October 29, 2011 23:06
Show Gist options
  • Select an option

  • Save fronx/1325209 to your computer and use it in GitHub Desktop.

Select an option

Save fronx/1325209 to your computer and use it in GitHub Desktop.
def rand5
rand(5) + 1
end
# n <= 25
def rand_n(n)
if (x = (((rand5 - 1) * 5) + rand5)) <= (25 - 25 % n)
(x % n) + 1
else
rand_n(n)
end
end
def rand7
rand_n(7)
end
def distr(n=10000)
distribution = []
n.times do
i = yield
distribution[i] ||= 0
distribution[i] += 1
end
distribution[1..-1].map do |i|
(i * (distribution.length - 1)).to_f / n
end
end
puts distr { rand5 }.inspect
puts distr { rand7 }.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment