forked from kaidul/LeetCode_problems_solution
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShuffle_an_Array.cpp
More file actions
32 lines (29 loc) · 785 Bytes
/
Shuffle_an_Array.cpp
File metadata and controls
32 lines (29 loc) · 785 Bytes
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
// Fisher Yates algorithm
class Solution {
vector<int> original;
vector<int> arr;
public:
Solution(vector<int> nums) {
srand(time(NULL));
arr = nums;
original = nums;
}
/** Resets the array to its original configuration and return it. */
vector<int> reset() {
return arr = original;
}
/** Returns a random shuffling of the array. */
vector<int> shuffle() {
for(int i = arr.size() - 1; i > 0; --i) {
int j = rand() % (i + 1);
swap(arr[i], arr[j]);
}
return arr;
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* vector<int> param_1 = obj.reset();
* vector<int> param_2 = obj.shuffle();
*/