|
18 | 18 | * [3] Knuth, Donald E. (1969). Seminumerical algorithms. The Art of Computer |
19 | 19 | * Programming Volume 2. |
20 | 20 | * [4] https://en.wikipedia.org/wiki/Fisher–Yates_shuffle |
| 21 | + * |
| 22 | + * @param {Function} randint The randint function. |
| 23 | + * @return {Function} The sampling function. |
21 | 24 | */ |
22 | | -const _fisheryates = (randint) => (n, a, i, j) => { |
23 | | - // We will swap at most n elements |
24 | | - // NOTE: When n = j - i, the last swap swaps a[j-1] with itself, |
25 | | - // which is a NOOP. /!\ HOWEVER, the last swap is NOT a NOOP when |
26 | | - // n < j - i. Hence we cannot let k = i + n - 1 in general. |
27 | | - const k = i + n; |
| 25 | +const _fisheryates = (randint) => { |
| 26 | + /** |
| 27 | + * Take a sample of size n (without repetitions) from the items i through |
| 28 | + * j-1 of the input array. This is done in-place. The sample can be |
| 29 | + * retrieved from position i to i+n. |
| 30 | + * |
| 31 | + * @param {number} n The size of the sample. |
| 32 | + * @param {Array} a The input array. |
| 33 | + * @param {number} i The inclusive left bound. |
| 34 | + * @param {number} j The non-inclusive right bound. |
| 35 | + */ |
| 36 | + const sample = (n, a, i, j) => { |
| 37 | + // We will swap at most n elements |
| 38 | + // NOTE: When n = j - i, the last swap swaps a[j-1] with itself, |
| 39 | + // which is a NOOP. /!\ HOWEVER, the last swap is NOT a NOOP when |
| 40 | + // n < j - i. Hence we cannot let k = i + n - 1 in general. |
| 41 | + const k = i + n; |
| 42 | + |
| 43 | + for (; i < k; ++i) { |
| 44 | + // Choose any index p in the remaining array |
28 | 45 |
|
29 | | - for (; i < k; ++i) { |
30 | | - // Choose any index p in the remaining array |
| 46 | + const p = randint(i, j); |
31 | 47 |
|
32 | | - const p = randint(i, j); |
| 48 | + // Swap element at index p with first element in the array |
33 | 49 |
|
34 | | - // Swap element at index p with first element in the array |
| 50 | + const tmp = a[i]; |
| 51 | + a[i] = a[p]; |
| 52 | + a[p] = tmp; |
| 53 | + } |
| 54 | + }; |
35 | 55 |
|
36 | | - const tmp = a[i]; |
37 | | - a[i] = a[p]; |
38 | | - a[p] = tmp; |
39 | | - } |
| 56 | + return sample; |
40 | 57 | }; |
41 | 58 |
|
42 | 59 | export default _fisheryates; |
0 commit comments