Algorithm


Problem Name: 384. Shuffle an Array

Problem Link: https://leetcode.com/problems/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.

 

Example 1:

Input
["Solution", "shuffle", "reset", "shuffle"]
[[[1, 2, 3]], [], [], []]
Output
[null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]

Explanation
Solution solution = new Solution([1, 2, 3]);
solution.shuffle();    // Shuffle the array [1,2,3] and return its result.
                       // Any permutation of [1,2,3] must be equally likely to be returned.
                       // Example: return [3, 1, 2]
solution.reset();      // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3]
solution.shuffle();    // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2]

 

Constraints:

  • 1 <= nums.length <= 50
  • -106 <= nums[i] <= 106
  • All the elements of nums are unique.
  • At most 104 calls in total will be made to reset and shuffle.
 



 
 

Code Examples

#1 Code Example with Java Programming

Code - Java Programming


class Solution {
    
    private int[] nums;
    private Random random;

    public Solution(int[] nums) {
        this.nums = nums;
        random = new Random();
    }
    
    public int[] reset() {
        return nums;
    }
    
    public int[] shuffle() {
        if (nums == null) return null;
        int[] shuf = nums.clone();
        for (int i=1;i < shuf.length;i++) {
            int l = random.nextInt(i+1);
            swap(shuf, i, l);
        }
        
        return shuf;
    }
    
    private void swap(int[] arr, int a, int b) {
        int temp = arr[a];
        arr[a] = arr[b];
        arr[b] = temp;
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
["Solution", "shuffle", "reset", "shuffle"] [[[1, 2, 3]], [], [], []]

Output

x
+
cmd
[null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]

#2 Code Example with Javascript Programming

Code - Javascript Programming


const Solution = function(nums) {
  this.original = nums;
};

Solution.prototype.reset = function() {
  return this.original;
};

Solution.prototype.shuffle = function() {
  const res = [];
  const len = this.original.length;
  let idx = 0;
  let i = 0;
  while (idx  < = len - 1) {
    i = Math.floor(Math.random() * len);
    if (res[i] == null) {
      res[i] = this.original[idx];
      idx += 1;
    }
  }
  return res;
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
["Solution", "shuffle", "reset", "shuffle"] [[[1, 2, 3]], [], [], []]

Output

x
+
cmd
[null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]

#3 Code Example with Python Programming

Code - Python Programming


class Solution:

    def __init__(self, nums: List[int]):
        self.arr = nums
        self.org = nums[:]

    def reset(self) -> List[int]:
        """
        Resets the array to its original configuration and return it.
        """
        self.arr = self.org[:]
        return self.arr

    def shuffle(self) -> List[int]:
        """
        Returns a random shuffling of the array.
        """
        random.shuffle(self.arr)
        return self.arr


# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.reset()
# param_2 = obj.shuffle()
Copy The Code & Try With Live Editor

Input

x
+
cmd
["Solution", "shuffle", "reset", "shuffle"] [[[1, 2, 3]], [], [], []]

Output

x
+
cmd
[null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]
Advertisements

Demonstration


Previous
#383 Leetcode Ransom Note Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#385 Leetcode Mini Parser Solution in C, C++, Java, JavaScript, Python, C# Leetcode