#1

Hey so I solved the level but am trying to fully comprehend the code.

``````while(true) {
var farthest = null;
var maxDistance = 0;
var enemyIndex = 0;
var enemies = hero.findEnemies();

// Look at all the enemies to figure out which one is farthest away.
while (enemyIndex < enemies.length) {
var target = enemies[enemyIndex];
enemyIndex += 1;

// Is this enemy farther than the farthest we've seen so far?
var distance = hero.distanceTo(target);
if (distance > maxDistance) {
maxDistance = distance;
farthest = target;
}
}
``````

so each time enemyIndex will increase by 1. if my distance to the target is greater than 0 then 0 is my distance to the target.? I tried taking out maxDistance=distance and it worked the same (I figured repeating 0 seemed redundant?)

I tried taking out enemyIndex +=1 but it didnâ€™t work, if the code loop returns true, shouldnâ€™t it move on to the next piece? Like my looking at this how does it know to keep moving further until there are no more targets? When you move closer to another target doesnâ€™t that bring the remaining targets further from your location resulting in an infinite loop? or is that why (enemyIndex < enemies.length) is there so that it stops when it hits the last enemy? (I think I just answered my own question) so is it necessary to put maxDistance = distance?

#2

every enemy has a distance, the var max distance is just a default value, to get the enemy max distance you have no choice but to compare all the enemies distances. So that is why the variable maxdistance is re-assigned to the variable distance

removing the enemyIndex += 1 wonâ€™t work because this is a while loop and the condition is based on the value of enemyIndex. So if enemyIndex canâ€™t equal enemies.length, the loop is endless.

It could result in an infinite loop you are right on that, but I believe the way the enemy is attacked is also a while loop, while the health of the farthest is > 0. which is why also the loop is not endless because the enemy get killed before all the code restart.

like I said before there is more than 1 way of doing those kind of problems, I always prefer for loops for those

#3

Hey! Just wanted to put a little note here so that people can go there for reference. Gabriel helped me understand what was going on here in my other thread Not understanding the code ! Thanks again Gabriel!