1

I try to call multiple times a method that draw an element from an array using probabilities.

My first method (first_function) is a promise that when resolved return this array :

[
  [
    {
      cardName: "Energy Fire",
      cardRatio: 50,
    },
    {
      cardName: "Energy Water",
      cardRatio: 50,
    },
  ],
  [
    {
      cardName: "Charizard",
      cardRatio: 10,
    },
    {
      cardName: "Pikachu",
      cardRatio: 30,
    },
    {
      cardName: "Rayquaza",
      cardRatio: 60,
    },
  ],
];

When the promise is resolved, i call another method (second_function) :

my_promise.then((result) => {
  for (const position in result) {
    this.second_function(result[position]);
  }
});

There is my second method (second_function) :

function second_function(pull) {
  var winner = Math.random() * 100;
  var threshold = 0;
  for (let i = 0; i < pull.length; i++) {
    threshold += pull[i].cardRatio;
    if (threshold > winner) {
      return console.log("winner", pull[i]);
    }
  }
}

I want to draw a random card from each array (this is why i call multiple times second_function in the first_function) but the problem is just one draw is resolved (i see just one console.log). However, second_function is called multiple times like expected but it looks like the for loop in the second_function is called one time only.

MarioG8
  • 5,122
  • 4
  • 13
  • 29
  • maybe you should print the `winner` – kid-joker Dec 06 '21 at 09:16
  • in this case, the winner is just the random number choosed for the pull, the real winner result is ```pull[i]``` – François Biscuit Dec 06 '21 at 09:20
  • The term you're after is weight. – Estus Flask Dec 06 '21 at 09:33
  • See https://stackoverflow.com/questions/8435183/generate-a-weighted-random-number – Estus Flask Dec 06 '21 at 09:33
  • Oh ok! Thanks for the documentation, so my var "winner" is the weight. Any ideas what is wrong in my code ? – François Biscuit Dec 06 '21 at 10:00
  • Yes. You're not normalizing weights. `100` should be a sum of weights in a group, or `threshold` should be divided by a sum. With your current implementation you'll likely need 2 loops to achieve that. Consider checking algos in the dupe question – Estus Flask Dec 06 '21 at 12:14
  • I'm sorry i'm a little bit confused about what i need to do... I check some other topics before coding my script and i found this one : https://stackoverflow.com/questions/16346112/get-random-item-for-array-based-on-different-probabilities I used the same script than the answers, are they incorrect too ? – François Biscuit Dec 06 '21 at 15:00

0 Answers0