Simpler code for random subset problem

#1

If you generate the subset at the beginning instead of at the end, you can simplify all the == null and != null checks:

    public static int[] computeRandomSubset(int n, int k) {
        Map<Integer, Integer> changed = new HashMap<>();
        Random r = new Random();

        int[] subset = new int[k];
        for (int i = 0; i < k; i++) {
            subset[i] = i;
        }

        for (int i = 0; i < k; i++) {
            int pos = i + r.nextInt(n - i);
            if (pos < subset.length) { //we are inside array, swap just those 2 elements, don't change the map
                swap(subset, i, pos);
            } else {  //outside of the array, check if the index was changed using a map
                int temp = subset[i];
                subset[i] = changed.containsKey(pos) ? changed.get(pos) : pos;
                changed.put(pos, temp);
            }
        }

        return subset;
    }
0 Likes