-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path384.shuffle_an_array.cpp
53 lines (48 loc) · 1.45 KB
/
384.shuffle_an_array.cpp
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
//coding:utf-8
/***********************************************************
Program: Shuffle an array
Description:
Shanbo Cheng: [email protected]
Date: 2016-08-12 21:56:33
Last modified: 2016-08-12 21:59:06
GCC version: 4.9.3
***********************************************************/
#include <vector>
#include <random>
using namespace std;
//the idea is simple
//The idea is simple, just using two vectors to store the numbers, one is original, one is to be shuffled.
//The shuffle algorithm is the Knuth Shuffle:
//
//Randomly choose a value in the vector from 0 ... size. (size is initialized of vector.size() - 1)
//Swap the value with the size-th last value of the vector
//Reduce the size by 1.
//Go to 1 while size > 0
//
class Solution {
vector<int> original;
vector<int> shuf;
public:
Solution(vector<int> nums) {
original = nums;
shuf = nums;
}
/** Resets the array to its original configuration and return it. */
vector<int> reset() {
return original;
}
/** Returns a random shuffling of the array. */
vector<int> shuffle() {
if(shuf.empty())
return shuf;
for(int i = shuf.size(); i > 0; --i)
swap(shuf[rand() % i], shuf[i - 1]);
return shuf;
}
};
/**
* 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();
*/