-
Notifications
You must be signed in to change notification settings - Fork 4
/
Knuth.h
72 lines (64 loc) · 2.15 KB
/
Knuth.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#ifndef CH1_KNUTH_H
#define CH1_KNUTH_H
#include <vector>
#include <random>
using std::vector;
using std::uniform_int_distribution;
using std::swap;
std::random_device rd;
std::mt19937 gen(rd());
/**
* The {@code Knuth} class provides a client for reading in a
* sequence of strings and <em>shuffling</em> them using the Knuth (or Fisher-Yates)
* shuffling algorithm. This algorithm guarantees to rearrange the
* elements in uniformly random order, under
* the assumption that Math.random() generates independent and
* uniformly distributed numbers between 0 and 1.
* <p>
* For additional documentation,
* see <a href="https://algs4.cs.princeton.edu/11model">Section 1.1</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
* See {@link StdRandom} for versions that shuffle arrays and
* subarrays of objects, doubles, and ints.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
class Knuth {
public:
// this class should not be instantiated
Knuth() = delete;
/**
* Rearranges an array of objects in uniformly random order
* (under the assumption that {@code Math.random()} generates independent
* and uniformly distributed numbers between 0 and 1).
* @param a the array to be shuffled
*/
template<typename T>
static void shuffle(vector<T> &a) {
int n = a.size();
for (int i = 0; i < n; i++) {
// choose index uniformly in [0, i]
uniform_int_distribution<> dis(0, i);
int r = dis(gen);
swap(a[r], a[i]);
}
}
/**
* Rearranges an array of objects in uniformly random order
* (under the assumption that {@code Math.random()} generates independent
* and uniformly distributed numbers between 0 and 1).
* @param a the array to be shuffled
*/
template<typename T>
static void shuffleAlternate(vector<T> &a) {
int n = a.size();
for (int i = 0; i < n; i++) {
// choose index uniformly in [i, n-1]
uniform_int_distribution<> dis(0, n - i);
int r = i + dis(gen);
swap(a[r], a[i]);
}
}
};
#endif //CH1_KNUTH_H