1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| package simpleGa;
public class FitnessCalc {
static byte[] solution = new byte[64];
/* Public methods */
// Set a candidate solution as a byte array
public static void setSolution(byte[] newSolution) {
solution = newSolution;
}
// To make it easier we can use this method to set our candidate solution
// with string of 0s and 1s
static void setSolution(String newSolution) {
solution = new byte[newSolution.length()];
// Loop through each character of our string and save it in our byte
// array
for (int i = 0; i < newSolution.length(); i++) {
String character = newSolution.substring(i, i + 1);
if (character.contains("0") || character.contains("1")) {
solution[i] = Byte.parseByte(character);
} else {
solution[i] = 0;
}
}
}
// Calculate inidividuals fittness by comparing it to our candidate solution
static int getFitness(Individual individual) {
int fitness = 0;
// Loop through our individuals genes and compare them to our cadidates
for (int i = 0; i < individual.size() && i < solution.length; i++) {
if (individual.getGene(i) == solution[i]) {
fitness++;
}
}
return fitness;
}
// Get optimum fitness
static int getMaxFitness() {
int maxFitness = solution.length;
return maxFitness;
}
} |
Partager