Skip to content

Commit 49b7b19

Browse files
📚 docs(sample/_fisheryates): Document function signatures.
1 parent 21c8bdd commit 49b7b19

File tree

2 files changed

+42
-14
lines changed

2 files changed

+42
-14
lines changed

src/api/sample.js

+11
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,16 @@
11
import _fisheryates from '../kernel/_fisheryates.js';
22
import randint from './randint.js';
33

4+
/**
5+
* Take a sample of size n (without repetitions) from the items i through
6+
* j-1 of the input array. This is done in-place. The sample can be retrieved
7+
* from position i to i+n.
8+
*
9+
* @function
10+
* @param {number} n The size of the sample.
11+
* @param {Array} a The input array.
12+
* @param {number} i The inclusive left bound.
13+
* @param {number} j The non-inclusive right bound.
14+
*/
415
const sample = _fisheryates(randint);
516
export default sample;

src/kernel/_fisheryates.js

+31-14
Original file line numberDiff line numberDiff line change
@@ -18,25 +18,42 @@
1818
* [3] Knuth, Donald E. (1969). Seminumerical algorithms. The Art of Computer
1919
* Programming Volume 2.
2020
* [4] https://en.wikipedia.org/wiki/Fisher–Yates_shuffle
21+
*
22+
* @param {Function} randint The randint function.
23+
* @return {Function} The sampling function.
2124
*/
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
2845

29-
for (; i < k; ++i) {
30-
// Choose any index p in the remaining array
46+
const p = randint(i, j);
3147

32-
const p = randint(i, j);
48+
// Swap element at index p with first element in the array
3349

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+
};
3555

36-
const tmp = a[i];
37-
a[i] = a[p];
38-
a[p] = tmp;
39-
}
56+
return sample;
4057
};
4158

4259
export default _fisheryates;

0 commit comments

Comments
 (0)