Problem

Shuffle an Array

Approach

  1. Use Random.nextInt(N) to get a random index, and with that we can get a list of indices which are these indices of a new random list.
  2. The mentioned method also can be used as one of generating a permutation with equally likely.
  3. Thanks to the Solution part and there is one better solution. TBD.

Code

class Solution {
    private int[] original;
    private Random rand;

    public Solution(int[] nums) {
        original = nums;
        rand = new Random();
    }
    
    /** Resets the array to its original configuration and return it. */
    public int[] reset() {
        return this.original;
    }
    
    /** Returns a random shuffling of the array. */
    public int[] shuffle() {
        List<Integer> array = new ArrayList<>();
        for(int i = 0; i < original.length; i ++){
            array.add(original[i]);
        }
        int[] ans = new int[array.size()];
        for(int i = 0; i < original.length; i ++){
            int idx = rand.nextInt(array.size());
            ans[i] = array.get(idx);
            array.remove(idx);
        }
        return ans;
    }
}

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(nums);
 * int[] param_1 = obj.reset();
 * int[] param_2 = obj.shuffle();
 */