Skip to content
Advertisement

Sum of intervals in Java

I am stuck on this kata in CodeWars and I have tried for a long time, like for a week or so for one kata. If you want a description of my question, go here.

This is my code, if you believe me, there are lots of bugs in it. Can someone please help me out?

public static int sumIntervals(int[][] intervals) {
    int sum = 0;
    int[] currentLargeInterval = {intervals[0][0], intervals[0][0]};
    ArrayList<int[]> addedIntervals = new ArrayList<>();
    ArrayList<int[]> arrays = new ArrayList<>();
    addAll(arrays, intervals);
    ArrayList<int[]> removed = new ArrayList<>();
    for (int i = 0; i < arrays.size(); i++) {
        if (i > 0) {
            if (arrays.get(i - 1)[1] >= arrays.get(i)[0] && arrays.get(i - 1)[1] < arrays.get(i)[1]) {
                removed.add(arrays.get(i));
                currentLargeInterval[1] = arrays.get(i)[1];
            } else {
                addedIntervals.add(currentLargeInterval);
                currentLargeInterval = new int[]{arrays.get(i - 1)[0], arrays.get(i - 1)[0]};
            }
        }
    }
    addedIntervals.add(currentLargeInterval);
    arrays.removeAll(removed);
    arrays.addAll(addedIntervals);
    for (int[] a : arrays) {
        System.out.println(Arrays.toString(a));
    }
    return sum;
}

Advertisement

Answer

I think you are over-complicating the solution in general (which makes bugs harder to find), it seems that all that is really required is that you do not add duplicates in a Collection, and output the size of the collection afterward.

I whipped up a quick version of this (I only tried it out against 2 of the tests).

public static void main(String[] args) {
    int [][] intervals = {{1,5},{10, 20},{1, 6},{16, 19},{5, 11}};
    System.out.println(sumIntervals(intervals));
}

public static int sumIntervals(int [][] intervals) {
    ArrayList<Integer> values = new ArrayList<>();
    for (int [] row : intervals) {
        for (int k = row[0]; k < row[1]; k++) {
            if (!values.contains(k)) {
                values.add(k);
            }
        }
    }
    return values.size();
}

Output:

19

This solution first iterates against the outer array to obtain each range, then uses those values to iterate between them and add each number into a List if the number is not already in the List, by utilizing .contains().

Finally it returns the size of the List that contains each non-duplicated number.

3 People found this is helpful
Advertisement