Commit | Line | Data |
---|---|---|
41534b92 BA |
1 | // https://stackoverflow.com/a/47593316/12660887 |
2 | function mulberry32(a) { | |
3 | return function() { | |
4 | let t = a += 0x6D2B79F5; | |
5 | t = Math.imul(t ^ t >>> 15, t | 1); | |
6 | t ^= t + Math.imul(t ^ t >>> 7, t | 61); | |
7 | return ((t ^ t >>> 14) >>> 0) / 4294967296; | |
8 | } | |
9 | } | |
10 | ||
11 | export const Random = { | |
12 | ||
13 | rand: null, | |
14 | ||
15 | setSeed: function(a) { | |
16 | Random.rand = mulberry32(a); | |
17 | }, | |
18 | ||
19 | randInt: function(min, max) { | |
20 | if (!max) { | |
21 | max = min; | |
22 | min = 0; | |
23 | } | |
24 | if (!Random.rand) | |
33b42748 | 25 | Random.setSeed(Math.floor(Math.random() * 19840)); |
41534b92 BA |
26 | return Math.floor(Random.rand() * (max - min)) + min; |
27 | }, | |
28 | ||
29 | // Inspired by https://github.com/jashkenas/underscore | |
30 | sample: function(arr, n) { | |
31 | n = n || 1; | |
32 | let cpArr = arr.map(e => e); | |
33 | for (let index = 0; index < n; index++) { | |
bc2bc396 | 34 | const rand = Random.randInt(index, arr.length); |
41534b92 BA |
35 | [ cpArr[index], cpArr[rand] ] = [ cpArr[rand], cpArr[index] ]; |
36 | } | |
3b641716 BA |
37 | const res = cpArr.slice(0, n); |
38 | return (n >= 2 ? res : res[0]); | |
41534b92 BA |
39 | }, |
40 | ||
41 | shuffle: function(arr) { | |
bc2bc396 | 42 | return Random.sample(arr, arr.length); |
41534b92 BA |
43 | } |
44 | ||
45 | }; |