samedi 22 septembre 2018

Leetcode 384 - why does this doesn't work. Is there anything wrong with the random function?

class Solution {

    int[] arr;

    public Solution(int[] nums) {
        this.arr = nums.clone();
    }

    /** Resets the array to its original configuration and return it. */
    public int[] reset() {
        return this.arr;
    }

    /** Returns a random shuffling of the array. */
    public int[] shuffle() {
        int[] arr1 = this.arr.clone();
        for(int i = 0; i < arr1.length; i++){
            int a = (int)(Math.random())*(i+1);
            swap(arr1,i,a);
        }
        return arr1;
    }

    public void swap(int[] arr, int i, int j){
        int temp = arr[i];
        arr[i]=arr[j];
        arr[j]=temp;
    }


}

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

```

Why doesn't this work. It does genereate a random sequence in the shuffle method. For question: https://leetcode.com/problems/shuffle-an-array/description/




Aucun commentaire:

Enregistrer un commentaire