Shuffle an Array

Problem

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();

Solution

My Brute Force Solution, getting random index

public class Solution {

    int[] nums;
    Random random;

    public Solution(int[] nums) {
        this.nums = nums;
        this.random = new Random();
    }

    public int[] reset() {
        return this.nums;
    }

    public int[] shuffle() {
        int len = nums.length, index = 0;
        int[] res = new int[len];
        Set<Integer> set = new HashSet<>();
        while (index < len) {
            int i = random.nextInt(len);
            if (set.add(i)) res[index++] = nums[i]; 
        }
        return res;
    }

}

Swap Solution

public class Solution {

    int[] nums;
    Random random;

    public Solution(int[] nums) {
        this.nums = nums;
        this.random = new Random();
    }

    public int[] reset() {
        return this.nums;
    }

    public int[] shuffle() {
        if (nums == null || nums.length < 2) return nums;
        int[] res = nums.clone();
        for (int i = 1; i < nums.length; i++) {
            int j = random.nextInt(i + 1);
            if (i != j) swap(res, i, j);
        }
        return res;
    }

    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

Analysis

The key idea of this design is that we use swap
We loop through the entire array starting from the second element
Then we randomly pick a index j before i to make the swap j = random.nextInt(i + 1)
In this case, each index before i or including i can be chosen to swap with nums[i]
Hence it will make the shuffle satisfies the problem's requirement

results matching ""

    No results matching ""