Skip to content

Instantly share code, notes, and snippets.

@phellipeandrade
Created January 14, 2017 13:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phellipeandrade/7077034f0b2a248a316c7e2ac076360b to your computer and use it in GitHub Desktop.
Save phellipeandrade/7077034f0b2a248a316c7e2ac076360b to your computer and use it in GitHub Desktop.
//The sum of 'weights' elements should be equal 1.
let weights = [0.1, 0.9]; // probabilities
//The possible results
let results = [0, 1]; // values to return
function getRandom () {
let num = Math.random(),
s = 0,
lastIndex = weights.length - 1;
for (let i = 0; i < lastIndex; ++i) {
s += weights[i];
if (num < s) {
return results[i];
}
}
return results[lastIndex];
};
let number = getRandom()
let element = document.getElementById('box')
number === 1 ? element.setAttribute("class", "square-box blue") :
element.setAttribute("class", "square-box red")
console.log(number)
let timer = window.setTimeout(() => {
location.reload(true)
}, 1000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment