Penn Penn - 1 month ago 10
Javascript Question

Loop through array of items using probability

I am pretty new to JavaScript and I have been making while-loops that rolls a dice and breaks out of the loop when you roll a 6.

var rollDice = function() {
var dice = Math.floor(Math.random() * 6 + 1);

while (dice !== 6) {
console.log("A " + dice + " was rolled!");
var dice = Math.floor(Math.random() * 6 + 1)
}
console.log("Lucky! You rolled a 6!");
}


Now I want to loop through an array of items and break out of it when a desired item is found. I want to be able to declare the desired item like this:

var desiredItem = "Diamond";


However, every item has its own probability value that I would like to include in this while-loop. This would mean that you have a 25% chance of getting a rusty nail while only a 5% chance of receiving a diamond. So statistically you would be getting more rusty nails than diamonds. I also would like to output everything to the user inside the loop, like this:

console.log("Dang! A " + lootedItem + " was found...");


and when you finally receive the desired item and break out the loop:

console.log("Lucky! A" + desiredItem + "was found!");


I have been trying on my own for a while now but cant seem to get it, so any help would be appreciated. Thanks!

Answer

Here is an ES6 implementation for that:

var findItem = function(desiredItem) {
    var items = [
        { item: "rusty nail", probability: 0.25 },
        { item: "stone", probability: 0.23 },
        { item: "banana", probability: 0.20 },
        { item: "leaf", probability: 0.17 },
        { item: "mushroom", probability: 0.10 },
        { item: "diamond", probability: 0.05 }
    ];
    var possible = items.some( ({item, probability}) => 
          item === desiredItem && probability > 0 );
    if (!possible) {
        console.log('There is no chance you\'ll ever find a ' + desiredItem);
        return;
    }
    var sum = items.reduce( (sum, {item, probability}) => sum+probability, 0 );
    while (true) {
        var value = Math.random() * sum;
        var lootedItem = items.find( 
                ({item, probability}) => (value -= probability) <= 0 ).item;
        if (lootedItem === desiredItem) break;
        console.log("Dang! A " + lootedItem + " was found...");
    }
    console.log("Lucky! A " + desiredItem + " was found!");
}

findItem('diamond');

Comments