// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: packimports(3) fieldsfirst 
// Source File Name:   Genetic.java

package lt.ktu.gmj.tasks;

import java.util.Random;

public class Genetic
{

	private int num_of_Items;
	private int num_of_population;
	public int Population[][];
	private Random rnd;

	Genetic(int Items, int pop)
	{
		rnd = new Random();
		num_of_population = pop;
		num_of_Items = Items;
		Population = new int[pop][];
		for(int i = 0; i < pop; i++)
			Population[i] = new int[Items];

	}

	public void mutation(int A1)
	{
		int position = (int)(Math.random() * (double)num_of_Items);
		if(Population[A1][position] == 1)
			Population[A1][position] = 0;
		else
			Population[A1][position] = 1;
	}

	public void cross(int A1)
	{
		int A2 = (int)(Math.random() * (double)num_of_population);
		int position = (int)(Math.random() * (double)num_of_Items);
		for(int i = 0; i < position; i++)
			Population[A1][i] = Population[A2][i];

		for(int i = position; i < num_of_Items; i++)
			Population[A2][i] = Population[A1][i];

	}

	public void generate()
	{
		for(int i = 0; i < num_of_population; i++)
		{
			for(int j = 0; j < num_of_Items; j++)
				Population[i][j] = 0;

		}

		for(int i = 0; i < num_of_population; i++)
		{
			int position = (int)(Math.random() * (double)num_of_Items);
			Population[i][position] = 1;
		}

	}

	public void reproduction(double Wealth[])
	{
		double sum = 0.0D;
		for(int i = 0; i < num_of_population; i++)
			sum += Wealth[i];

		int NewPopulation[][] = new int[num_of_population][];
		for(int i = 0; i < num_of_population; i++)
			NewPopulation[i] = new int[num_of_Items];

		for(int i = 0; i < num_of_population; i++)
		{
			double prob = rnd.nextDouble();
			double present = 0.0D;
			int pos = 0;
			for(int j = 0; j < num_of_population; j++)
			{
				if(i == 0)
				{
					if(prob > 0.0D && prob <= Wealth[i] / sum)
					{
						pos = j;
						break;
					}
				} else
				if(prob > present && prob <= present + Wealth[i] / sum)
				{
					pos = j;
					break;
				}
				present += Wealth[i] / sum;
			}

			for(int j = 0; j < num_of_Items; j++)
				NewPopulation[i][j] = Population[pos][j];

		}

		for(int i = 0; i < num_of_population; i++)
		{
			for(int j = 0; j < num_of_Items; j++)
				Population[i][j] = NewPopulation[i][j];

		}

	}
}
