1 10 package examples.audit; 11 12 import org.jgap.*; 13 14 20 public class CoinsExampleFitnessFunction 21 extends FitnessFunction { 22 23 private final static String CVS_REVISION = "$Revision: 1.3 $"; 24 25 private final int m_targetAmount; 26 27 public static final int MAX_BOUND = 1000; 28 29 public CoinsExampleFitnessFunction(int a_targetAmount) { 30 if (a_targetAmount < 1 || a_targetAmount >= MAX_BOUND) { 31 throw new IllegalArgumentException ( 32 "Change amount must be between 1 and " + MAX_BOUND + " cents."); 33 } 34 m_targetAmount = a_targetAmount; 35 } 36 37 50 public double evaluate(IChromosome a_subject) { 51 int changeAmount = amountOfChange(a_subject); 63 int totalCoins = getTotalNumberOfCoins(a_subject); 64 int changeDifference = Math.abs(m_targetAmount - changeAmount); 65 double fitness = (MAX_BOUND - 1 - changeDifference * 20); 73 if (changeDifference == 0) { 78 fitness += computeCoinNumberBonus(totalCoins); 79 } 80 return Math.max(1.0d, fitness); 83 } 84 85 protected double computeCoinNumberBonus(int a_coins) { 86 return MAX_BOUND - ( (MAX_BOUND * 0.05d) * a_coins); 87 } 88 89 100 public static int amountOfChange(IChromosome a_potentialSolution) { 101 int numQuarters = getNumberOfCoinsAtGene(a_potentialSolution, 0); 102 int numDimes = getNumberOfCoinsAtGene(a_potentialSolution, 1); 103 int numNickels = getNumberOfCoinsAtGene(a_potentialSolution, 2); 104 int numPennies = getNumberOfCoinsAtGene(a_potentialSolution, 3); 105 return (numQuarters * 25) + (numDimes * 10) + (numNickels * 5) + 106 numPennies; 107 } 108 109 121 public static int getNumberOfCoinsAtGene(IChromosome a_potentialSolution, 122 int a_position) { 123 Integer numCoins = 124 (Integer ) a_potentialSolution.getGene(a_position).getAllele(); 125 return numCoins.intValue(); 126 } 127 128 137 public static int getTotalNumberOfCoins(IChromosome a_potentialsolution) { 138 int totalCoins = 0; 139 int numberOfGenes = a_potentialsolution.size(); 140 for (int i = 0; i < numberOfGenes; i++) { 141 totalCoins += getNumberOfCoinsAtGene(a_potentialsolution, i); 142 } 143 return totalCoins; 144 } 145 } 146 | Popular Tags |