import java.util.Random; /** Individual.java - For this example, we just want an array of 10 integers. */ public class Individual { public static final int SIZE = 10; public static final int LOW = 1; public static final int HIGH = 5000; public int [] a; public int fitness; /** Default constructor: Create 10 integers, each selected randomly. */ public Individual() { a = new int[SIZE]; for (int i = 0; i < SIZE; ++i) a[i] = randomAlleleValue(); // Calculate my fitness. this.fitness = this.findFitness(); } /** randomAlleleValue - for this example we want a random * number in the range 1..5000 or LOW..HIGH in general. */ public static int randomAlleleValue() { // Use the system clock to set the random number generator. Random gen = new Random(System.nanoTime()); return gen.nextInt(HIGH - LOW + 1) + LOW; } /** findFitness - Find the fitness of one individual, this. * For this simple exercise, this will mean how many * numbers in my array end in 8 or 9. * Also store result in the fitness attribute. */ public int findFitness() { int count = 0; for (int i = 0; i < SIZE; ++i) if (a[i] % 10 == 8 || a[i] % 10 == 9) ++count; this.fitness = count; return count; } /** toString - show the fitness value and the alleles. * Be careful with the syntax. */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append(String.format("fitness %2d (", this.findFitness())); for (int i = 0; i < SIZE - 1; ++i) sb.append(String.format("%d, ", a[i])); sb.append(String.format("%d)", a[SIZE - 1])); return sb.toString(); } }