Straight-forward C++ solution

• Straight-forward solution

``````class Solution {
vector<int> nums;
public:
Solution(vector<int> nums) {
this->nums = nums;
}

/** 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> result(nums);
for (int i = 0;i < result.size();i++) {
int pos = rand()%(result.size()-i);
swap(result[i+pos], result[i]);
}
return result;
}
};

/**
* 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();
*/
``````

• This post is deleted!

• @haruhiku I believe you should not do rand() % (i+1). E.g. if you get i+1 = 7, and the rand_max is 50 (simplified for our case), the rand() will get 0~50 uniformly, but after %7 you get one more 0 than 6's.

I don't know how to generate random numbers within a range in C++. Java has Random.nextInt(upper_bound+1) to do this.

• This post is deleted!

• "Notice though that this modulo operation does not generate uniformly distributed random numbers in the span (since in most cases this operation makes lower numbers slightly more likely)."

• @wei88 Oh, my bad. Thanks for the explanation.

• Very nice solution ! thanks for sharing

• @Louis1992 Hi, nice solution! Thank you for your sharing. Can I ask why we don't need `srand` to initialize a random number generator? When I run the customer testcase, the results of `shuffle()` are not changed.

• @wtsanshou Hah in reality you need. I just save code to pass the test!

• @wtsanshou BTW, `srand`should be call in constructor, because the leetcode judge the answer "...any permutation of [1,2,3] must equally likely to be returned..", so call in function `shuffle` will cause wrong answer.

• Now your could cannot pass the test, it got TLE error.