Skip to content

Instantly share code, notes, and snippets.

@vividness
Created August 22, 2013 21:26
Show Gist options
  • Save vividness/6313004 to your computer and use it in GitHub Desktop.
Save vividness/6313004 to your computer and use it in GitHub Desktop.
Biased randomness with probability weights vector
# Work in progress
#
# This function generates the vector
#
# examples:
# [3, 2, 2, 1]
# [5, 4, 4, 3, 3, 3, 2, 2, 2, 2, 1, 1, 1, 1, 1]
def probability_weights_vector(n)
n.downto(1).reduce([]) { |ary, i|
ary.push(*([i] * (n -i + 1)))
}
end
# get the vector
v = probability_weights_vector(5)
# calculate the vector length
v_range = (0..v.size-1)
# this is where we will put
# the summary
summary ||= {}
# Run throught the loop for 1000 times
# and keep track of the distribution
1000.times {
returned = v[rand(r_param)]
summary["returned_#{returned}"] ||= 0
summary["returned_#{returned}"] += 1
}
# OK, print out the results
# and see the distribution
p res.sort
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment