Created
October 14, 2009 15:17
-
-
Save rk/210151 to your computer and use it in GitHub Desktop.
This file contains 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
# Ruby translation of: http://kaioa.com/node/53#comment-477 | |
probabilities = [1, 1, 1, 1, 1, 1]; | |
unrandomness = 1; | |
def cumsum(vector) | |
_dup = vector.dup | |
1.upto(_dup.length - 1) { |i| _dup[i] += _dup[i-1] } | |
_dup | |
end | |
puts "roll | probabilities" | |
6.times do | |
# find the cumulative probability, and then divide each member | |
# by the sum of the probabilities. | |
cumprob = cumsum(probabilities) | |
_sum = probabilities.reduce(:+).to_f | |
cumprob.map! { |n| n / _sum } | |
# find the first index greater than the cumulative probability | |
_rand = rand | |
roll = cumprob.index(cumprob.find { |prob| prob >= _rand }) | |
# add unrandomness... | |
probabilities.map! { |n| n + unrandomness } | |
probabilities[roll] -= 6*unrandomness | |
if (_min = probabilities.min) < 0 | |
probabilities.map! { |n| n - _min } | |
end | |
# pretty printing for the eyes | |
print " #{roll + 1} | " | |
probabilities.each { |p| print p.to_s.center(4) } | |
puts | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment