Created
June 8, 2015 20:38
-
-
Save mdouglass/917760363c487d8799b8 to your computer and use it in GitHub Desktop.
Little Puzzlers - Fun With Random numbers
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
describe('randomness', () => { | |
function rand5() { | |
let low = 1; | |
let high = 5; | |
return Math.floor(Math.random() * (high - low + 1) + low); | |
} | |
function createGenerator(min, max, func) { | |
return { next: func, min, max }; | |
} | |
function widen(generator) { | |
return createGenerator(1, generator.max * generator.max, () => { | |
let x = generator.next(); | |
let y = generator.next(); | |
return (x - 1) * generator.max + y; | |
}) | |
} | |
function narrow(generator, max) { | |
return createGenerator(1, max, () => { | |
do { | |
let v = generator.next(); | |
if (v <= max) | |
return v; | |
} while(true); | |
}) | |
} | |
function changeMax(generator, max) { | |
while (generator.max < max) | |
generator = widen(generator); | |
if (generator.max > max) | |
generator = narrow(generator, max); | |
return generator; | |
} | |
function showDistribution(generator) { | |
let results = []; | |
for (var i = 0; i < 100000; ++i) { | |
let v = generator.next() - 1; | |
results[v] = results[v] || 0; | |
results[v]++; | |
} | |
console.log(results, results.map((v) => v / 100000)) | |
} | |
it('show distributions', () => { | |
let Rand5 = createGenerator(1, 5, rand5); | |
showDistribution(Rand5); | |
showDistribution(changeMax(Rand5, 4)); | |
showDistribution(changeMax(Rand5, 7)); | |
showDistribution(changeMax(Rand5, 30)); | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment