Created
July 8, 2021 03:28
-
-
Save mittsh/68f0faf2bf89d64846ec8907f582ca83 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
const randomPlusRandom = () => Math.random() + Math.random() | |
const randomTwoTimesRandom = () => 2 * Math.random() | |
// call `fn()` count-times | |
// and return the results as an array | |
const getSequence = (fn, count) => { | |
return Array | |
// create an array of `count` elements | |
.from(Array(count).keys()) | |
// call `fn()` count-times | |
.map(() => fn()) | |
} | |
const getIntervals = (sequence, nIntervals) => { | |
const intervalWidth = 2 / nIntervals | |
// intervals | |
let intervals = Object.fromEntries( | |
Array | |
.from(Array(nIntervals).keys()) | |
.map((el) => [Math.round(el).toString(), 0]) | |
) | |
// loop over `sequence` to categorize each item | |
sequence.forEach((item) => { | |
// floor of each interval | |
const intervalFloor = Math.floor(item / intervalWidth) | |
intervals[intervalFloor.toString()] += 1 | |
}) | |
// convert to a list | |
return Object.entries(intervals) | |
.map(([key, value]) => | |
`${(parseInt(key, 10) * intervalWidth)}\t${value}` | |
) | |
.join('\n') | |
} | |
console.log(getIntervals(getSequence(randomPlusRandom, 100000), 20)) | |
console.log(getIntervals(getSequence(randomTwoTimesRandom, 100000), 20)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment