Move Zeroes

Code on Github

Advertisements

Shuffle an Array



    //Note: the problem states that this is a set without duplicates which makes building all combinations easier
    
    private List<List> combinations;
    private int[] original;
    private Random random;
    
    public Solution(int[] nums) {
        original = nums;
        random = new Random();
        combinations = buildAllComb(nums);
    }
    
    //insert next value into all possible positions, I wrote this method myself, of course it could be simplified to not use a queue
    //but it just naturally came into my mind that I used a queue
    private List<List> buildAllComb(int[] nums) {
        List<List> result = new ArrayList<List>();
        if(nums == null || nums.length == 0) return result;
        
        List list = new ArrayList();
        list.add(nums[0]);
        Queue<List> q = new LinkedList();
        q.offer(list);
        for(int i = 1; i < nums.length; i++){
            int qSize = q.size();
            for(int k = 0; k < qSize; k++){
                List currList = q.poll();
                for(int j = 0; j <= currList.size(); j++){
                    List newL = new ArrayList(currList);
                    newL.add(j, nums[i]);
                    q.offer(newL);
                }
            }
        }
        while(!q.isEmpty()){
            result.add(q.poll());
        }
        return result;
    }

    /** Resets the array to its original configuration and return it. */
    public int[] reset() {
        return original;
    }
    
    /** Returns a random shuffling of the array. */
    public int[] shuffle() {
        if(original == null || original.length == 0) return original;
        int randomIndex = random.nextInt(combinations.size());
        List list = combinations.get(randomIndex);
        int[] result = new int[list.size()];
        for(int i = 0; i < list.size(); i++){
            result[i] = list.get(i);
        }
        return result;
    }


Code on Github