Programming library  » Articles Articles
Roulette Wheel

» Roulette Wheel

Page: 1 of 1
By: Daniel
Last updated: 20 April

Most game programmers and the ones using evolutionary programming faced this problem. You have to randomly pick an element from a set, each element having a weight. Example:
Weight ( a )=2
Weight ( b )=1
These means that a has twice as much chances as b to be picked. In this case the answer is simple: We will generate a random number in the interval [0,3) . For 0 and 1 we will pick a and b for 2.

We can extend this principle for an entire set. Lets consider and array of N weights. A simple algorithm to pick and element is:
S <- 0
For I=1 to N do
	S<- S+Weight(i)
R<- Choose a random number in the interval [0,S)
S2<-0
P<-0
While  S2+Weight(P+1)<=R do
	P<-P+1
	S2<-S2+Weight(P)
End while

Picked=P
This algorithm is acceptable for average amount of data. We should look for some improvements if we take the case of a genetic algorithm that is using millions of roulette wheel selections. There are several selections using the same data set. We could reuse the S obtained at the first step. We could also reuse the partial sums calculated after we choose R at the price of some extra memory usage used for storing them. The initialization of the algorithm will look like:
PS - partial sums array
S<-0
For I=1 to N do
	S<-S+Weight(i)
	PS(i)<-PS(i)+1
End for
We can use the partial sums when making a selection. PS is an order array so we can use a binary search to find the picked element. It doesn't look like a serious improvement for small cases but when dealing with millions of weights and selections you will notice a difference.
R<- Choose random number in the interval [0,S)
Start<-1
End<-N
While Start<= N do
	Mid<-(Start+End)/2
	If R>=PS(Mid) then
		Start<-Mid+1
	End if
	If R<=PS(Mid) then
		End<-Mid-1
	End if
End while

Picked=Start
I suggest using an object-oriented approach. The partial sums will be computed in the initialization part and a method for the actual selection.
Pages: 1
Programming help
Do you have problems
with your code?
Please send your question to: askphp@stdlib.com
Somebody will try to help you.

Articles
ProgrammingProgramming
    » Two Programmers
    » Make and Makefiles

AlgorithmsAlgorithms
    » Roulette Wheel

DataData
    » Shortcut File Format (.lnk)

WebWeb
    » Installing PHP on your PC

MediaMedia

Stdlib WebsiteStdlib Website
    » How to add an article
    » Stdlib.com Rules


Small?
Small but growing!


Do you know where to get programming help? ... Stdlib.com !