Skip to content

Instantly share code, notes, and snippets.

@scottgreenup
Created December 7, 2017 00:00
Show Gist options
  • Save scottgreenup/91b62aa356e29e251eb3f5b7cffd79e1 to your computer and use it in GitHub Desktop.
Save scottgreenup/91b62aa356e29e251eb3f5b7cffd79e1 to your computer and use it in GitHub Desktop.
Possible random value generator
const crypto = require('crypto')
/**
* Generates an evenly distributed random number.
* Basically, keep performing rounds until we have one champion. Each round a
* random number is generated for every remaining character in choices. If the
* random number is a maximum, those characters go onto the next round, until
* there is only one maximum left.
*/
function randomValue(characterList) {
let choices = characterList
while (choices.length !== 1) {
let rv = crypto.randomBytes(choices.length)
let max = 0
for (let i = 1; i < rv.length; i++) {
if (rv[i] > rv[max]) {
max = i
}
}
let choicesNext = ''
for (let i = 0; i < choices.length; i++) {
if (rv[i] == rv[max]) {
choicesNext += choices[i]
}
}
choices = choicesNext
}
return choices[0]
}
// Test it out :)
const characterList = '0123456789'
let d = new Map()
for (let i = 0; i < 10000000; i++) {
rv = randomValue(characterList)
if (d.has(rv) !== true) {
d.set(rv, 1)
} else {
d.set(rv, d.get(rv) + 1)
}
}
for (let j = 0; j < characterList.length; j++) {
const c = characterList[j]
console.log(`${c}: ${d.get(c)}`)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment