1 10 package org.jgap.perf; 11 12 import org.jgap.*; 13 14 20 public class TestOverallPerformanceFitnessFunc 21 extends FitnessFunction { 22 23 24 private final static String CVS_REVISION = "$Revision: 1.3 $"; 25 26 private final int m_targetAmount; 27 28 public TestOverallPerformanceFitnessFunc(int a_targetAmount) { 29 if (a_targetAmount < 1 || a_targetAmount > 999) { 30 throw new IllegalArgumentException ( 31 "Change amount must be between 1 and 999 cents."); 32 } 33 m_targetAmount = a_targetAmount; 34 } 35 36 45 public double evaluate(IChromosome a_subject) { 46 int changeAmount = amountOfChange(a_subject); 58 int totalCoins = getTotalNumberOfCoins(a_subject); 59 int changeDifference = Math.abs(m_targetAmount - changeAmount); 60 int fitness = (99 - changeDifference); 69 if (changeAmount == m_targetAmount) { 74 fitness += 100 - (10 * totalCoins); 75 } 76 return Math.max(1, fitness); 79 } 80 81 91 public static int amountOfChange(IChromosome a_potentialSolution) { 92 int numQuarters = getNumberOfCoinsAtGene(a_potentialSolution, 0); 93 int numDimes = getNumberOfCoinsAtGene(a_potentialSolution, 1); 94 int numNickels = getNumberOfCoinsAtGene(a_potentialSolution, 2); 95 int numPennies = getNumberOfCoinsAtGene(a_potentialSolution, 3); 96 int A = getNumberOfCoinsAtGene(a_potentialSolution, 4); 97 int B = getNumberOfCoinsAtGene(a_potentialSolution, 5); 98 int C = getNumberOfCoinsAtGene(a_potentialSolution, 6); 99 int D = getNumberOfCoinsAtGene(a_potentialSolution, 7); 100 int E = getNumberOfCoinsAtGene(a_potentialSolution, 8); 101 int F = getNumberOfCoinsAtGene(a_potentialSolution, 9); 102 return (numQuarters * 25) + (numDimes * 10) + (numNickels * 5) 103 + numPennies + (A * 29) + (B * 31) + (C * 37) + (D * 41) + (E * 43) 104 + (F * 47); 105 } 106 107 116 public static int getNumberOfCoinsAtGene(IChromosome a_potentialSolution, 117 int a_position) { 118 Integer numCoins = 119 (Integer ) a_potentialSolution.getGene(a_position).getAllele(); 120 return numCoins.intValue(); 121 } 122 123 130 public static int getTotalNumberOfCoins(IChromosome a_potentialsolution) { 131 int totalCoins = 0; 132 int numberOfGenes = a_potentialsolution.size(); 133 for (int i = 0; i < numberOfGenes; i++) { 134 totalCoins += getNumberOfCoinsAtGene(a_potentialsolution, i); 135 } 136 return totalCoins; 137 } 138 } 139 | Popular Tags |