import java.lang.Math.*; import java.util.*; /** * Roulette is a class implementing fitness-proportionate selection via * a biased roulette wheel. * * @author Simon Levy * @version %I%, %G% * @since JDK1.2 */ import DPFPArrays.*; public class Roulette { // wheel size is inverse of smallest encodable probability private static final int SIZE = 1000; // random-number generator private Random m_rand; // biased roulette wheel private int [] m_wheel = new int [SIZE]; /** * Creates a roulette wheel with arbitrary initial conditions. * * @param fits population fitnesses * */ public Roulette(double [] fits) { m_rand = new Random(); construct(fits); } /** * Creates a roulette wheel with seed for random-number generator, * to support reproducible results. * * @param fits population fitnesses * @param seed seed for random-number generator * */ public Roulette(double [] fits, long seed) { m_rand = new Random(seed); construct(fits); } /** * "Rolls the wheel" to get an integer in [0,N), where N is the number * of fitness values specified in the constructor. * * @return an integer in [0,N) */ public int roll() { // generate a random index in [0,SIZE) int index = m_rand.nextInt(SIZE); // pick the number at that index in the wheel return m_wheel[index]; } // build a roulette wheel using specified probabilities. private void construct(double [] fits) { // normalize fitnesses to probabilities in (0,1) by dividing by sum double [] probs = DPFPArrays.normalize(fits); // fill the wheel array with integers corresponding to each position, // represented proportionally by probability int beg = 0; for (int i=0; i