-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshuffle_an_array.cpp
53 lines (46 loc) · 1.02 KB
/
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
// 384. Shuffle an Array: https://leetcode.com/problems/shuffle-an-array
// Author: [email protected]
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <algorithm>
#include <vector>
using std::vector;
class Solution
{
public:
Solution(vector<int>& nums): nums_(nums)
{
srand(time(NULL));
}
/** Resets the array to its original configuration and return it. */
vector<int> reset()
{
return nums_;
}
/** Returns a random shuffling of the array. */
vector<int> shuffle()
{
vector<int> nums(nums_);
int size = nums.size();
for (int i = 0; i < size; i++)
{
int j = rand() % size;
std::swap(nums[i], nums[j]);
}
return nums;
}
private:
vector<int> nums_;
};
int main(int argc, char* argv[])
{
vector<int> nums = {1, 2, 3};
auto digits = Solution(nums).shuffle();
for (const auto val: digits)
{
printf("%d ", val);
}
printf("\n");
return 0;
}