I developed Java code similar to Java Dan Dyer (link to it earlier). However, my roulette wheel selects one element based on a probability (input) vector and returns the index of the selected element. Having said that, the following code is more appropriate if the selection size is unitary, and if you do not assume how probabilities are calculated and a value of zero probability is allowed. The code is self-contained and includes a 20-wheel test (to run).
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; public class RouletteWheel { public int select(List<Double> wheelProbabilities, Random rng) throws Exception{ double[] cumulativeProba = new double[wheelProbabilities.size()]; cumulativeProba[0] = wheelProbabilities.get(0); for (int i = 1; i < wheelProbabilities.size(); i++) { double proba = wheelProbabilities.get(i); cumulativeProba[i] = cumulativeProba[i - 1] + proba; } int last = wheelProbabilities.size()-1; if (cumulativeProba[last] != 1.0) { throw new Exception("The probabilities does not sum up to one (" + "sum="+cumulativeProba[last]); } double r = rng.nextDouble(); int selected = Arrays.binarySearch(cumulativeProba, r); if (selected < 0) { selected = Math.abs(selected + 1); } int i = selected; while (wheelProbabilities.get(i) == 0.0){ System.out.print(i+" selected, correction"); i--; if (i<0) i=last; } selected = i; return selected; } public static void main(String[] args){ RouletteWheel rw = new RouletteWheel(); int rept = 20; List<Double> P = new ArrayList<>(4); P.add(0.2); P.add(0.1); P.add(0.6); P.add(0.1); Random rng = new Random(); for (int i = 0 ; i < rept; i++){ try { int s = rw.select(P, rng); System.out.println("Element selected "+s+ ", P(s)="+P.get(s)); } catch (Exception ex) { Logger.getLogger(RouletteWheel.class.getName()).log(Level.SEVERE, null, ex); } } P.clear(); P.add(0.2); P.add(0.0); P.add(0.5); P.add(0.0); P.add(0.1); P.add(0.2);
Below the sample run for the sample vector P = [0,2,0,1,0,6,0,1], WheelElements = [0,1,2,3]:
Element selected 3, P (s) = 0.1
Element selected 2, P (s) = 0.6
Element selected 3, P (s) = 0.1
Element selected 2, P (s) = 0.6
Element selected 1, P (s) = 0.1
Element selected 2, P (s) = 0.6
Element selected 3, P (s) = 0.1
Element selected 2, P (s) = 0.6
Element selected 2, P (s) = 0.6
Element selected 2, P (s) = 0.6
Element selected 2, P (s) = 0.6
Element selected 2, P (s) = 0.6
Element selected 3, P (s) = 0.1
Element selected 2, P (s) = 0.6
Element selected 2, P (s) = 0.6
Element selected 2, P (s) = 0.6
Element selected 0, P (s) = 0.2
Element selected 2, P (s) = 0.6
Element selected 2, P (s) = 0.6
Element selected 2, P (s) = 0.6
The code also checks the roulette wheel with zero probability.