Last active
October 16, 2019 14:43
-
-
Save ptasheq/9e8897f2e31e063934a69fcce4da4128 to your computer and use it in GitHub Desktop.
Generate a sequence of unique random integers
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
| // Credit to Jeff Preshing | |
| // https://preshing.com/20121224/how-to-generate-a-sequence-of-unique-random-integers/ | |
| class RandomSequenceOfUnique { | |
| constructor(intermediateOffset, seedBase=1) { | |
| this.index = permuteQPR(permuteQPR(seedBase) + 0x682f0161); | |
| this.intermediateOffset = intermediateOffset; | |
| } | |
| getNext() { | |
| const next = this.getNth(this.index); | |
| ++this.index; | |
| } | |
| getNth(n) { | |
| // >>> ensures conversion to unsigned int | |
| return permuteQPR(((permuteQPR(n) + this.intermediateOffset) ^ 0x5bf03635) >>> 0); | |
| } | |
| } | |
| function permuteQPR(x) { | |
| const prime = 4294967291; | |
| const halfPrime = 2147483645; | |
| if (x >= prime) | |
| return x; // The 5 integers out of range are mapped to themselves. | |
| // squaring can cause exceeding 2^53 | |
| const residue = Number((BigInt(x) * BigInt(x)) % BigInt(prime)); | |
| return (x <= halfPrime) ? residue : prime - residue; | |
| } | |
| // permuteQPR can be useful for generating some fancy intermediateOffset | |
| module.exports = {RandomSequenceOfUnique, permuteQPR} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment