-1

I'm very new to JavaScript.

So I'm trying to create a discord bot. I want to randomly choose a value from an array and then display it, but I want some elements to be more likely to be chosen than others. I'm attempting to do this with percentages.

This is everything I have done so far:

var locations = ['cave', 'house', 'bin', 'haroon`s mansion'];
var chance = [30, 30, 35, 5];
var randomValue = Math.random() * 100;

Now, how do I make it choose one and send it back? Please could you explain what each command does?

Daemon Beast
  • 2,794
  • 3
  • 12
  • 29
haroon_tk
  • 77
  • 2
  • 9

1 Answers1

1

Keep track of a running sum of percentages, and pick when you're finally underneath the sum:

const locations = ['cave', 'house', 'bin', 'haroon`s mansion'];
const chance = [30, 30, 35, 5];

const randomValue = Math.random() * 100;
let runningSum = 0;
let choice;
for (let i = 0; i < chance.length ; i ++) {
    runningSum += chance[i];
    if (randomValue <= runningSum) {
        choice = locations[i];
        break;
    }
}

console.log(choice);
Aplet123
  • 33,825
  • 1
  • 29
  • 55
  • Thank you. Could you explain how it works? – haroon_tk Dec 16 '20 at 21:18
  • @haroon_tk Essentially, this creates a range for each probability, where the ranges are directly touching each other and the size of the range is the probability. If you're less than the upper bound of the range, you know that you're greater than the lower bound due to having made it that far in the loop, which means that the choice has been found. – Aplet123 Dec 16 '20 at 21:31
  • Thank you so much. – haroon_tk Dec 16 '20 at 21:39
  • I'm not sure if I just can't make it work or it is intended. randomValue<= runningSum means that if the number is above 35, then it'll return as undefined because there is no location that is above that number. I tried and it does return undefined. – user874737 Jan 28 '23 at 00:47