lundi 29 mai 2017

JavaScript biased results?

Let's say I have two items in an array, e.g:

["a", "b"]

Now let's say I have a function called random that chooses a random item from this array, e.g:

function random() {
  // do awesome random stuff here...
  return random_choice;
}

How can I get the random function to return "a" 80% of the time and "b" 20% of the time?

I'm not really sure as to what this is called but for example if I ran the console.log(random()); 10 times the result should look a little something like this:

>>> "a"
>>> "a"
>>> "a"
>>> "a"
>>> "a"
>>> "a"
>>> "a"
>>> "a"
>>> "b"
>>> "b"

"a" get's returned 8/10 times and "b" gets returned 2/10 times.

NOTE: the "results" above are just an example, I understand that they won't always be that perfect and they don't have to be.




Aucun commentaire:

Enregistrer un commentaire