[LeetCode] Shuffle an Array

384. Shuffle an Array

Given an integer array nums, design an algorithm to randomly shuffle the array. All permutations of the array should be equally likely as a result of the shuffling.

Implement the Solution class:

  • Solution(int[] nums) Initializes the object with the integer array nums.
  • int[] reset() Resets the array to its original configuration and returns it.
  • int[] shuffle() Returns a random shuffling of the array.

Fisher–Yates shuffle

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
class Solution {
vector<int> _origin;
vector<int> _shuffle;
public:
Solution(vector<int>& nums) {
_origin = vector<int>(nums.begin(), nums.end());
_shuffle = vector<int>(_origin.begin(), _origin.end());
}

vector<int> reset() {
_shuffle = vector<int>(_origin.begin(), _origin.end());
return _shuffle;
}

vector<int> shuffle() {
for(int i = 0; i < _shuffle.size(); i++) {
swap(_shuffle[rand() % _shuffle.size()], _shuffle[i]);
}
return _shuffle;
}
};

/**
* 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();
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/08/PS/LeetCode/shuffle-an-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.