Skip to content

Instantly share code, notes, and snippets.

@rk
Created October 14, 2009 15:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rk/210151 to your computer and use it in GitHub Desktop.
Save rk/210151 to your computer and use it in GitHub Desktop.
# 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