/*
 *      Genalg.java
 *      
 *      Copyright 2011 Paul Cockshott <wpc@prescott.dcs.gla.ac.uk>
 *      
 *      
 *      
 *      
 */

import java.util.Random;
import java.util.Arrays;
 
public class Genalg {
	
    Gene [] population;
    int n;
    
    public Genalg(int n,Gene g ){
	this.n = n;		 
	population = new Gene[n];
	population[0] = g;
	for (int i=1;i<n;i++) population[i] = g.mutate();
	Arrays.sort(population);
    }

    public Genalg(Gene[]initialPopulation){
	n = initialPopulation.length;		 
	population = initialPopulation;
	Arrays.sort(population);
    }

    void showPop(){for (Gene g : population) System.out.println(g);}

    public Gene theBest(){return population[n-1];}

    public void optimise(int cycles){
	Random randomGenerator = new Random();
	for(int i=1;i<=cycles;i++){
	    int randomInt = randomGenerator.nextInt(n);
	    Gene g = population[randomInt];
	    int j = randomGenerator.nextInt(n-randomInt)+randomInt;
	    //System.out.println("crossover: "+ randomInt +" "+ j);
	    if (randomGenerator.nextInt(2)==1) g = g.crossover(population[j]);
	    else g = g.mutate();
	    //System.out.println(g);
	    //System.out.println(population[j]);
	    //g = g.crossover(population[j]);
	    //System.out.println(g);
	    //g = g.mutate();
	    //System.out.println("new offspring is\n"+g+"...");
	    float f = g.fitness;
	    int first = 0;int upto = n;
	    boolean identical = false;
	    while (first < upto) {
		int mid = (first + upto) / 2;  // Compute mid point.
		if (f < population[mid].fitness) {
		    upto = mid;     // repeat search in bottom half.
		} else if (f > population[mid].fitness) {
		    first = mid + 1;  // Repeat search in top half.
		} else {
		    identical = g.hash == population[mid].hash;
		    break;
		}
	    }
	    if(!identical)
		for(j=0;j<n;j++){
		    if(f>population[j].fitness) {
			if (j<(n-1)){
			    if(f>population[j+1].fitness)
				population[j] = population[j+1];
			    else {population[j] = g; break;}			    
			}
			else population[j] = g;
		    }		    
		}
	}
    }
    
    public static void main (String args[]) {
	int N=32;int pop=24;
	for(int j=0;j<10;j++) {
	    Gene g = new Permutor1(N, new SillyEvaluator());
	    Genalg alg = new Genalg(pop,g);
	    for(int i=0;i<2000;i++){
		//alg.showPop();
		//System.out.println("-----------------");
		alg.optimise(1);
		System.out.println(""+N+","+(pop+i)+","+alg.population[pop-1].fitness);
	    }
	}
    }
}