/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package genetic;

import java.util.HashSet;
import java.util.Random;
import jm.music.data.Phrase;

/**
 *
 * @author smuRf
 */
public class Selection {
    private Phrase[] chromosomes;
    private double[] fitness;
    private int selectionSize;
    private int tourSize;
    
    public Selection(Phrase[] chromosomes, double[] fitness, int tourSize)
    {
        this.chromosomes = chromosomes;
        this.fitness = fitness;
        this.tourSize = tourSize;
        
        selectionSize = this.chromosomes.length / 3 * 2;
    }
    
    public Phrase[] tourSelect()
    {
        Phrase[] selectedChromosomes = new Phrase[selectionSize];
        HashSet<Integer> selectedIndizes = new HashSet();
        int[] tour = new int[tourSize];
        int cntChromosome = 0;
        Random rnd = new Random();
        
        while(cntChromosome < selectionSize)
        {
            int i = 0;
            while(i < tourSize)
            {
                int index = rnd.nextInt(chromosomes.length);
                if(!selectedIndizes.contains(index))
                {
                    tour[i] = index;
                    i++;
                }
            }
            
            double maxFitness = Double.MIN_VALUE;
            int maxFitnessTourIndex = 0;
            for(int j = 0; j < tour.length; j++)
            {
                if(fitness[tour[j]] > maxFitness)
                {
                    maxFitness = fitness[tour[j]];
                    maxFitnessTourIndex = j;
                }
            }
            
            selectedChromosomes[cntChromosome] = chromosomes[tour[maxFitnessTourIndex]].copy();
            selectedIndizes.add(tour[maxFitnessTourIndex]);
            cntChromosome ++;
        }
        
        return selectedChromosomes;
    }
}
