Ask coding questions

← Back to all posts
There are no syntax errors but the code still dosent work!(javascript)
h
JULIODIAZ1 (47)

Im making a Genetitc Algorithm (to learn more about genetic algorithms click here )and im trying to determine the fitness value but when i do they all come out as 5 and im stumped as to why so pls can someone help my code is here: https://replit.com/@JULIODIAZ1/Genetic-Algorithm

Answered by notGilbert (78) [earned 5 cycles]
View Answer
Comments
hotnewtop
notGilbert (78)

The = in the if statements are messing it up

= is used for assignment, == / === is used for comparison

Right now, you are setting the value of gene1 to H and it returns H (meaning true in JavaScript)

fix:

// change = to ===
if (gene1 === fitness_letters[0]) {
    agent.fitness += 1;
} else {
    agent.fitness -= 0.5;
}

// same thing here
if (gene2 === fitness_letters[1]) {
    agent.fitness += 1;
} else {
    agent.fitness -= 0.5;
}

// do this for everything else

this occurs 5 times (one for each gene) and everytime it += 1, which is where the 5 comes from

DynamicSquid (4624)

On line 32:

if(gene1 = fitness_letters[0]){

It's supposed to be the comparison operator, not the assignment operator