Fix 64-bits bug

This commit is contained in:
2026-10-14 22:59:26 +02:00
parent 5b213e3414
commit 0a899a7e09
4 changed files with 13 additions and 8 deletions

View File

@@ -20,7 +20,7 @@ public class Main {
break;
case 2:
SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm(
50,
15,
0.5,
0.025,
5,

View File

@@ -6,12 +6,13 @@ import lombok.Data;
@Data
public class Individual {
protected int defaultGeneLength = 64;
private byte[] genes = new byte[defaultGeneLength];
private byte[] genes;
private int fitness = 0;
public Individual(byte[] solution) {
for (int i = 0; i < genes.length; i++) {
genes = new byte[solution.length];
for (int i = 0; i < solution.length; i++) {
byte gene = (byte) Math.round(Math.random());
genes[i] = gene;
}
@@ -28,13 +29,17 @@ public class Individual {
fitness = 0;
}
public int getGenesCount(){
return genes.length;
}
public void recomputeFitness(byte[] solution) {
this.fitness = computeFitness(solution);
}
private int computeFitness(byte[] solution) {
int fitness = 0;
for (int i = 0; i < this.getDefaultGeneLength() && i < solution.length; i++) {
for (int i = 0; i < this.genes.length && i < solution.length; i++) {
if (this.getSingleGene(i) != solution[i]) continue;
fitness++;
}

View File

@@ -86,7 +86,7 @@ public class Population {
private Individual crossover(Individual indiv1, Individual indiv2, byte[] solution) {
Individual newSol = new Individual(solution);
for (int i = 0; i < newSol.getDefaultGeneLength(); i++) {
for (int i = 0; i < newSol.getGenesCount(); i++) {
newSol.setSingleGene(i, Math.random() <= uniformRate
? indiv1.getSingleGene(i)
: indiv2.getSingleGene(i));
@@ -96,7 +96,7 @@ public class Population {
}
private void mutate(Individual indiv) {
for (int i = 0; i < indiv.getDefaultGeneLength(); i++) {
for (int i = 0; i < indiv.getGenesCount(); i++) {
if (Math.random() <= mutationRate) {
byte gene = (byte) Math.round(Math.random());
indiv.setSingleGene(i, gene);

View File

@@ -28,8 +28,8 @@ public class SimpleGeneticAlgorithm extends AbstractGeneticAlgorithm{
@Override
protected void run() {
System.out.println("Generation: " + getGenerationCount() + " Correct genes found: " + population.getFittest().getFitness());
population = population.evolve(elitism, getSolution());
System.out.println("Generation: " + getGenerationCount() + " Correct genes found: " + population.getFittest().getFitness());
}
@Override