38. Shuffle an Array
13 Jul 2020 | Daily Algorithms
class Solution {
vector<int> arr, idx;
public:
Solution(vector<int>& nums) {
srand(time(NULL)); // generate random
arr.resize(nums.size());
idx.resize(nums.size());
for(int i = 0; i<nums.size();i++)
{
arr[i] = nums[i];
idx[i] = nums[i];
}
}
/** Resets the array to its original configuration and return it. */
vector<int> reset() {
for(int i = 0; i<arr.size();i++)
{
arr[i] = idx[i];
}
return arr;
}
/** Returns a random shuffling of the array. */
vector<int> shuffle() {
int i,j;
for(i = arr.size() -1; i>0; i--)
{
j = rand() % (i+1); // 0,1,2중으로 계속 나오는 것
swap(arr[i],arr[j]); // 0,1,2 어레이중의 데이터를 스왑하는 것 랜덤적으로
}
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();
*/
class Solution {
vector<int> arr, idx;
public:
Solution(vector<int>& nums) {
srand(time(NULL)); // generate random
arr.resize(nums.size());
idx.resize(nums.size());
for(int i = 0; i<nums.size();i++)
{
arr[i] = nums[i];
idx[i] = nums[i];
}
}
/** Resets the array to its original configuration and return it. */
vector<int> reset() {
for(int i = 0; i<arr.size();i++)
{
arr[i] = idx[i];
}
return arr;
}
/** Returns a random shuffling of the array. */
vector<int> shuffle() {
int i,j;
for(i = arr.size() -1; i>0; i--)
{
j = rand() % (i+1); // 0,1,2중으로 계속 나오는 것
swap(arr[i],arr[j]); // 0,1,2 어레이중의 데이터를 스왑하는 것 랜덤적으로
}
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();
*/
Comments