Shuffle An Array
Shuffle a set of numbers without duplicates.
Example:
// Init an array with set 1, 2, and 3. int[] nums = {1,2,3}; Solution solution = new Solution(nums); // Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned. solution.shuffle(); // Resets the array back to its original configuration [1,2,3]. solution.reset(); // Returns the random shuffling of array [1,2,3]. solution.shuffle();
1 public class Solution { 2 private int[] nums; 3 private Random random; 4 5 public Solution(int[] nums) { 6 this.nums = nums; 7 random = new Random(); 8 } 9 10 /** Resets the array to its original configuration and return it. */ 11 public int[] reset() { 12 return nums; 13 } 14 15 /** Returns a random shuffling of the array. */ 16 public int[] shuffle() { 17 if (nums == null) return nums; 18 19 int[] temp = nums.clone(); 20 for (int i = 1; i < temp.length; i++) { 21 int j = random.nextInt(i + 1); 22 swap(temp, i, j); 23 } 24 return temp; 25 } 26 27 private void swap(int[] nums, int i, int j) { 28 int temp = nums[i]; 29 nums[i] = nums[j]; 30 nums[j] = temp; 31 } 32 } 33 34 /** 35 * Your Solution object will be instantiated and called as such: 36 * Solution obj = new Solution(nums); 37 * int[] param_1 = obj.reset(); 38 * int[] param_2 = obj.shuffle(); 39 */