|
| 1 | +// Source : https://leetcode.com/problems/shuffle-an-array/ |
| 2 | +// Author : Hao Chen |
| 3 | +// Date : 2016-08-24 |
| 4 | + |
| 5 | +/*************************************************************************************** |
| 6 | + * |
| 7 | + * Shuffle a set of numbers without duplicates. |
| 8 | + * |
| 9 | + * Example: |
| 10 | + * |
| 11 | + * // Init an array with set 1, 2, and 3. |
| 12 | + * int[] nums = {1,2,3}; |
| 13 | + * Solution solution = new Solution(nums); |
| 14 | + * |
| 15 | + * // Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must |
| 16 | + * equally likely to be returned. |
| 17 | + * solution.shuffle(); |
| 18 | + * |
| 19 | + * // Resets the array back to its original configuration [1,2,3]. |
| 20 | + * solution.reset(); |
| 21 | + * |
| 22 | + * // Returns the random shuffling of array [1,2,3]. |
| 23 | + * solution.shuffle(); |
| 24 | + ***************************************************************************************/ |
| 25 | + |
| 26 | +class Solution { |
| 27 | +public: |
| 28 | + Solution(vector<int> nums) : _nums(nums), _solution(nums) { |
| 29 | + srand(time(NULL)); |
| 30 | + } |
| 31 | + |
| 32 | + /** Resets the array to its original configuration and return it. */ |
| 33 | + vector<int> reset() { |
| 34 | + return _solution = _nums; |
| 35 | + } |
| 36 | + |
| 37 | + /** Returns a random shuffling of the array. */ |
| 38 | + vector<int> shuffle() { |
| 39 | + //Fisher Yates |
| 40 | + //https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle |
| 41 | + |
| 42 | + int i = _solution.size(); |
| 43 | + |
| 44 | + while ( --i > 0 ) { |
| 45 | + int j = rand() % (i+1); |
| 46 | + swap(_solution[i], _solution[j]); |
| 47 | + } |
| 48 | + return _solution; |
| 49 | + } |
| 50 | +private: |
| 51 | + vector<int> _nums, _solution; |
| 52 | +}; |
| 53 | + |
| 54 | +/** |
| 55 | + * Your Solution object will be instantiated and called as such: |
| 56 | + * Solution obj = new Solution(nums); |
| 57 | + * vector<int> param_1 = obj.reset(); |
| 58 | + * vector<int> param_2 = obj.shuffle(); |
| 59 | + */ |
0 commit comments