# while loop unexpected behaviour (at least for me :) )

Hi All,

I am learning Julia by implementing code from the book of ‘Genetic Algorithm in python’. Because I also want to learn more GA. This refers to finding magic squares via GA in Simulated Annealing(chapter 8).

I have notice a certain type of behavior which I can’t explain but happens. I think it is specific to the while loop but I could be wrong.

The initial parent is made and then it calculates the fitness. Age at this point is 0. The function ‘taking_sample’ swaps to values in the parent and this becomes the child, the child’s fitness is tested against the existing parent. If it is better (lower is better). Then it is taken as parent and the whole process is started over again.

What I expect is that the swap is made, fitness calculated and if this is not better (or equal) it reverts back to the initial parent and does a new swap.

What actually happens is that it makes the swap from the original parent and then keeps swapping from the child. So it does not revert back to the parent and to start a new swap.

Can someone explain why this behavior is happening? Is it a logical mistake I am making?

I know that the while loop counter needs to be a global variable but i can’t s

Any feedback is welcome!

Best,

Alexander Chen

``````function main_loop(number)

parent = generate_matrix(number)
parent_fitness = first(summing(parent))
constant = magic_constant(number)

age = 0

while parent_fitness != 0

child = taking_sample(parent)
child_fitness = first(summing(child))

age += 1

if abs(child_fitness) <= abs(parent_fitness)
println("fitness dropped to \$(child_fitness), age was: \$(age)")
parent = copy(child)
parent_fitness = first(summing(parent))
age = 0
display(parent)
else
continue
end
end
println("this is the correct lay-out with a magic constant of \$(constant)")
return parent
end
``````

Welcome!