// 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:   AbstractRunner.java

package drm.genetics;

import java.util.*;

// Referenced classes of package drm.genetics:
//			Individual, Runner, Task

public abstract class AbstractRunner
	implements Runner
{

	protected TreeSet individuals;
	protected Random random;
	protected int stepCount;
	protected Task task;
	protected boolean interupted;

	public AbstractRunner()
	{
		individuals = new TreeSet();
		random = new Random();
		stepCount = 0;
		task = null;
		interupted = false;
	}

	public Individual getIndividual(int nr)
		throws IndexOutOfBoundsException
	{
		Iterator it = individuals.iterator();
		Object ob = null;
		int i;
		for(i = -1; it.hasNext() && i < nr; i++)
			ob = it.next();

		if(i == nr)
		{
			it.remove();
		} else
		{
			ob = null;
			throw new IndexOutOfBoundsException("index = " + String.valueOf(nr));
		}
		return (Individual)ob;
	}

	public void addIndividual(Individual individual)
	{
		individuals.add(individual);
	}

	protected double getRandomFunction()
	{
		return random.nextDouble() * random.nextDouble();
	}

	public Individual getRandomIndividual()
	{
		int nr = (int)(getRandomFunction() * (double)individuals.size());
		nr = Math.max(0, Math.min(individuals.size() - 1, nr));
		return getIndividual(nr);
	}

	public void init(Task task)
	{
		this.task = task;
		Individual ind[] = task.createIndividuals();
		individuals.clear();
		for(int i = 0; i < ind.length; i++)
			addIndividual(ind[i]);

	}

	public synchronized void start()
	{
		for(; !interupted && ((Individual)individuals.first()).getWeight() < task.getRequeredWeight(); step());
		interupted = false;
	}

	public synchronized void stop()
	{
		interupted = true;
	}

	public void step(int n)
	{
		for(int i = 0; i < n && ((Individual)individuals.first()).getWeight() < task.getRequeredWeight(); i++)
			step();

	}

	public Collection accessIndivids()
	{
		return individuals;
	}

	public int getAge()
	{
		return stepCount;
	}
}
