Skip to content

Commit

Permalink
deterministic shuffling (#190)
Browse files Browse the repository at this point in the history
fixes #189
note: shuffling is here to increase performance (#83)
  • Loading branch information
Fil committed Feb 28, 2022
1 parent cfbdb22 commit 9e0ac43
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/array.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
import lcg from "./lcg.js";

export default function(x) {
return typeof x === "object" && "length" in x
? x // Array, TypedArray, NodeList, array-like
: Array.from(x); // Map, Set, iterable, string, or anything else
}

export function shuffle(array) {
var m = array.length,
const random = lcg();
let m = array.length,
t,
i;

while (m) {
i = Math.random() * m-- | 0;
i = random() * m-- | 0;
t = array[m];
array[m] = array[i];
array[i] = t;
Expand Down
9 changes: 9 additions & 0 deletions src/lcg.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// https://en.wikipedia.org/wiki/Linear_congruential_generator#Parameters_in_common_use
const a = 1664525;
const c = 1013904223;
const m = 4294967296; // 2^32

export default function() {
let s = 1;
return () => (s = (a * s + c) % m) / m;
}
13 changes: 13 additions & 0 deletions test/pack/deterministic-test.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 9e0ac43

Please sign in to comment.