Mad Maxer help with arrays

Sorry for the long time with no answer, was a bit busy with some other topics…

You should have already encountered some levels where you used arrays. The general scheme is always the same:

//This saves the best candidate.
var best = null;

//This is the attribute to optimize. Usually you can rank objects against each other by some metric, for example maxHP or distance
var bestRating = -999999; //To maximize
var bestRating = 999999;  //To minimize    Only take one line depending on problem

//A simple loop-index, so we can iterate over the array
var index = 0;

var entities = getEntities(); //Here goes this.findItems(), this.findEnemies() ect.

while (i < entities.length){
    var rating = computeRating(entities[i]);
    if (rating > bestRating) { //to maximize, or < to minimize
        bestRating = rating;
        best = entities[i];
    }
    
    i = i+1;
}

//do something with best

If for example you would like to attack the enemy with the most health, you would use the following:

var healthiest = null;
var mostHP = -999999; //It is a maximizing-problem
var index = 0;
var enemies = this.getEnemies();

while (i < enemies.length){
    var hp = enemies[i].maxHealth;
    if (hp > mostHP) { //we want to get the most health
        mostHP = hp;
        healthiest = enemies[i];
    }
    
    i = i+1;
}

while(healthiest.health > 0){
    this.attack(healthiest);
}
1 Like