Diamond Dozen CPP - looking for help from python and JS coders

Arrays have been wooping my booooty… and my brain is just not wanting to understand I guess… I am looking over older levels but I just can’t figure out what I need to get my character to move! I know I am not putting the correct term down. Like coin.size or item.size or something… Maybe my array is just built wrong all together. Anyways, here is my code.

// Claim the coins while defeating the marauding ogres.

auto findMostHealth(auto enemies) {
    auto target = null;
    auto targetHealth = 0;
    int enemyIndex = 0;
    while(enemyIndex < enemies.size()) {
        auto enemy = enemies[enemyIndex];
        if(enemy.health > targetHealth) {
            target = enemy;
            targetHealth = enemy.health;
        }
        enemyIndex += 1;
    }
    return target;
}
auto valueOverDistance(auto item) {
    return item.value / hero.distanceTo(item);
}
auto findBestItem(auto items) {
    auto bestItem = null;
    auto bestValue = 0;
    int itemsIndex = 0;
   
    
    // Loop over the items array.
    // Find the item with the highest valueOverDistance()
    while(itemsIndex < items) {
        auto item = item[itemsIndex];
        if ( item.value / hero.distanceTo(item) > bestValue) {
             bestItem = coin;
            bestValue = valueOverDistance(item);
        } itemsIndex += 1;
    } 
    return bestItem;
}
int main() {
    
    while(true) {
        auto enemies = hero.findEnemies();
        auto enemy = findMostHealth(enemies);
        if(enemy && enemy.health > 15) {
            while(enemy.health > 0) {
                hero.attack(enemy);
            }
        } else {
            auto coins = hero.findItems();
            auto coin = null;
            coin = findBestItem(coins);
            if(coin) {
                hero.move(coin.pos);
            }
        }
    }
    return 0;
}

Code errors are not related to C ++. Anyone who has passed this level on their own without copying the solution from the net should be able to find minor code gaps, regardless of the programming language.

In fndBestItem, you’re setting bestItem = coin when coin is undefined.

1 Like

Yes , coin is undefined. The only offending function written in JS - find errors

// auto findBestItem(auto items)
// remove auto in function argument,
// replace all other auto or int  with var or let, put function instead of auto
function findBestItem(items) {
    var bestItem = null;
    var bestValue = 0;
    var itemsIndex = 0;

    while(itemsIndex < items) {
        var item = item[itemsIndex];
        if ( item.value / hero.distanceTo(item) > bestValue) {
             bestItem = coin;
            bestValue = valueOverDistance(item);
        } itemsIndex += 1;
    } 
    return bestItem;
}