Created
March 28, 2015 21:18
-
-
Save ezos86/68cfdf07c883269a43dd to your computer and use it in GitHub Desktop.
Percentage Chance on a Random Pick Function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var choices = [ | |
[10, "apples"], | |
[20, "oranges"], | |
[70, "bananas"] | |
]; | |
function pickChoice() { | |
rand = Math.floor(Math.random() * 100); | |
choice = -1; | |
for (i = 0; i < choices.length; i++) { | |
// set up min | |
if (i === 0) { | |
min = 0; | |
} else { | |
min = 0; | |
// add up all the values so far | |
for (i2 = 0; i2 < i; i2++) { | |
min += choices[i2][0]; | |
} | |
// one higher | |
min++; | |
} | |
// set up max | |
if (i === 0) { | |
max = choices[i][0]; | |
} else { | |
max = 0; | |
// add up all the values so far | |
for (i2 = 0; i2 < i + 1; i2++) { | |
max += choices[i2][0]; | |
} | |
} | |
if (rand >= min && rand <= max) { | |
choice = i; | |
break; | |
} | |
} | |
// If the choice is still -1 here, something went wrong... | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment