/** * @throws java.lang.IllegalArgumentException if the intervals are not optimized * @see QueryInterval#optimizeIntervals(QueryInterval[]) */ private void assertIntervalsOptimized(final QueryInterval[] intervals) { if (intervals.length == 0) return; for (int i = 1; i < intervals.length; ++i) { final QueryInterval prev = intervals[i-1]; final QueryInterval thisInterval = intervals[i]; if (prev.compareTo(thisInterval) >= 0) { throw new IllegalArgumentException(String.format("List of intervals is not sorted: %s >= %s", prev, thisInterval)); } if (prev.overlaps(thisInterval)) { throw new IllegalArgumentException(String.format("List of intervals is not optimized: %s intersects %s", prev, thisInterval)); } if (prev.abuts(thisInterval)) { throw new IllegalArgumentException(String.format("List of intervals is not optimized: %s abuts %s", prev, thisInterval)); } } }
/** * @param inputIntervals WARNING: This list is modified (sorted) by this method. * @return Ordered list of intervals in which abutting and overlapping intervals are merged. */ public static QueryInterval[] optimizeIntervals(final QueryInterval[] inputIntervals) { if (inputIntervals.length == 0) return EMPTY_QUERY_INTERVAL_ARRAY; Arrays.sort(inputIntervals); final List<QueryInterval> unique = new ArrayList<QueryInterval>(); QueryInterval previous = inputIntervals[0]; for (int i = 1; i < inputIntervals.length; ++i) { final QueryInterval next = inputIntervals[i]; if (previous.abuts(next) || previous.overlaps(next)) { final int newEnd = ((previous.end == 0 || next.end == 0) ? 0 : Math.max(previous.end, next.end)); previous = new QueryInterval(previous.referenceIndex, previous.start, newEnd); } else { unique.add(previous); previous = next; } } if (previous != null) unique.add(previous); return unique.toArray(EMPTY_QUERY_INTERVAL_ARRAY); } }