Skip to content

Instantly share code, notes, and snippets.

@djave-co
Last active April 21, 2020 21:32
Show Gist options
  • Save djave-co/3cc2f86bfc82c93f0f1f78c48962d62e to your computer and use it in GitHub Desktop.
Save djave-co/3cc2f86bfc82c93f0f1f78c48962d62e to your computer and use it in GitHub Desktop.
A tiny object that can return random numbers with different biases
// Demo / visualisation:
// https://codepen.io/EightArmsHQ/pen/BaavyPQ
let WeightedRandom = {
random(){
return Math.random();
},
sphere(){
return (Math.sin(1-Math.random() * 2 * Math.PI)+1) / 2;
},
gradient(){
return Math.tan(Math.random()-1.22) / 2.4 + 1.1;
},
reverseGradient(){
return 1 - (Math.tan(Math.random()-1.22) / 2.4 + 1.1);
},
fire(){
return Math.pow(Math.random(), 0.2);
},
reverseFire(){
return 1 - (Math.pow(Math.random(), 0.2));
},
exponential(){
return Math.pow((Math.random()), 10);
},
reverseExponential(){
return 1 - (Math.pow((Math.random()), 10));
},
yesNo(){
return Math.random() > 0.5 ? 1 : 0;
},
stepped(amount){
// You should pass in amount, this is just for the demo
amount = amount || 0.2;
return Math.round(Math.random() / amount) * amount;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment