/*
 * RouletteSelection.java
 *
 * Created on 16. listopad 2005, 13:03
 *
 * To change this template, choose Tools | Options and locate the template under
 * the Source Creation and Management node. Right-click the template and choose
 * Open. You can then make changes to the template in the Source Editor.
 */

package cz.pcland.ga.selection;

import cz.pcland.ga.BaseIndividual;
import java.util.*;

public class RouletteSelection implements SelectionOperator{
    double roulette[];
    int rouletteSize;
    
    
    public String toString() {
        return "Roulette wheel 2";
    }
    
    
    
    public BaseIndividual select(BaseIndividual[] population, int popSize, double sumOfFitness) { //override base selection method
        double random = Math.random();
        int i;
        for(i=0;i<popSize;i++){
            if(random < roulette[i]) break;
        }
        return population[i];
    }
    
    public void onStart(BaseIndividual[] population) {
        roulette = new double[population.length];
        rouletteSize = population.length;
    }
    
    
    public void init(BaseIndividual[] population, double sumOfFitness){
        for(int i=0;i<rouletteSize;i++){
            roulette[i] = population[i].getFitness();
        }
        
        roulette[0] = roulette[0]/sumOfFitness;
        
        for(int i=1;i<rouletteSize-1;i++){
            roulette[i] = roulette[i]/sumOfFitness + roulette[i-1];
        }
        
        roulette[rouletteSize-1] = 1;
    }
    
    /** Creates a new instance of RouletteSelection */
    public RouletteSelection() {
        super();     
    }
    
}
