private static Ranges subtractRanges(Ranges ranges, Ranges toSubtract) { Ranges.Builder newRanges = Ranges.newBuilder(); List<Range> sortedRanges = Lists.newArrayList(ranges.getRangeList()); Collections.sort(sortedRanges, RANGE_COMPARATOR); List<Range> subtractRanges = Lists.newArrayList(toSubtract.getRangeList()); Collections.sort(subtractRanges, RANGE_COMPARATOR); int s = 0; for (Range range : ranges.getRangeList()) { Range.Builder currentRange = range.toBuilder(); for (int i = s; i < subtractRanges.size(); i++) { Range matchedRange = subtractRanges.get(i); if (matchedRange.getBegin() < currentRange.getBegin() || matchedRange.getEnd() > currentRange.getEnd()) { s = i; break; } currentRange.setEnd(matchedRange.getBegin() - 1); if (currentRange.getEnd() >= currentRange.getBegin()) { newRanges.addRange(currentRange.build()); } currentRange = Range.newBuilder(); currentRange.setBegin(matchedRange.getEnd() + 1); currentRange.setEnd(range.getEnd()); } if (currentRange.getEnd() >= currentRange.getBegin()) { newRanges.addRange(currentRange.build()); } } return newRanges.build(); }
private static Ranges subtractRanges(Ranges ranges, Ranges toSubtract) { Ranges.Builder newRanges = Ranges.newBuilder(); List<Range> sortedRanges = Lists.newArrayList(ranges.getRangeList()); Collections.sort(sortedRanges, RANGE_COMPARATOR); List<Range> subtractRanges = Lists.newArrayList(toSubtract.getRangeList()); Collections.sort(subtractRanges, RANGE_COMPARATOR); int s = 0; for (Range range : ranges.getRangeList()) { Range.Builder currentRange = range.toBuilder(); for (int i = s; i < subtractRanges.size(); i++) { Range matchedRange = subtractRanges.get(i); if (matchedRange.getBegin() < currentRange.getBegin() || matchedRange.getEnd() > currentRange.getEnd()) { s = i; break; } currentRange.setEnd(matchedRange.getBegin() - 1); if (currentRange.getEnd() >= currentRange.getBegin()) { newRanges.addRange(currentRange.build()); } currentRange = Range.newBuilder(); currentRange.setBegin(matchedRange.getEnd() + 1); currentRange.setEnd(range.getEnd()); } if (currentRange.getEnd() >= currentRange.getBegin()) { newRanges.addRange(currentRange.build()); } } return newRanges.build(); }