use binarySearch.frink
// This class generates random elements from a discrete set with a
// known distribution, for example, the frequency of letters in the English
// language.
class randomDistribution
{
 // An array of elements
var elements
 // The sum of probabilities
var sum
new[] :=
{
elements = new array
sum = 0
}
 // Adds an item with the specified probability.
add[item, prob] :=
{
sum = sum + prob
elements.push[ [item, prob, sum] ]
}
 // Selects a random item based on the specified probabilities.
random[] :=
{
z = randomFloat[0, sum]
index = binarySearch[elements, z, {|a,b| a <=> b@2}]
return elements@index@0
}
}
View or download randomDistribution.frink in plain text format
This is a program written in the programming language Frink.
For more information, view the Frink
Documentation or see More Sample Frink Programs.
Alan Eliasen was born 14705 days, 19 hours, 54 minutes ago.