/*
 * RouletteSelection2.java
 *
 * Created on 28. prosinec 2005, 22:36
 *
 * 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.*;
import cz.pcland.ga.*;
/**
 *
 * @author petr
 */
public class RouletteSelection2 implements SelectionOperator {
    
    /** Creates a new instance of RouletteSelection2 */
    public RouletteSelection2() {
        super();
    }
    
    public String toString() {
        return "Roulette wheel";
    }
    
    public void onStart(BaseIndividual[] population) {
        
    }
    
    public void init(BaseIndividual[] population, double sumOfFitness) {
       
    }
    
    /**
     * Returns individual from generation using roulette wheel selection.
     */
    public BaseIndividual select(BaseIndividual[] population, int popSize, double sumOfFitness){
        //double n = Math.random()*sumOfFitness;
        double n = Math.abs(MyRand.getInt()%sumOfFitness) + Math.random();
        double sum = 0;

        for(int i=0;i<popSize;i++){
            sum+=population[i].getFitness();
            if(sum > n){
                return population[i];
            }
        }
        
        return population[popSize-1];
    }
    
}
