com.formkiq.vision.crafter.RangeMerger Maven / Gradle / Ivy
/*
* Copyright (C) 2018 FormKiQ Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.formkiq.vision.crafter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang3.Range;
import com.formkiq.vision.util.RangeUtil;
/**
* Utility class to merge {@link Range}.
*
*/
public final class RangeMerger {
/**
* private constructor.
*/
private RangeMerger() {
// empty
}
/**
* Merge {@link List} {@link Range} together if possible.
* @param ranges {@link List} {@link Range}
* @return {@link List} {@link Range}
*/
public static List> mergeRanges(final List>> ranges) {
List> r = null;
for (List> rr : ranges) {
if (rr.size() > 1) {
if (r == null) {
r = rr;
} else {
r = merge(r, rr);
}
}
if (r == null) {
break;
}
}
return r;
}
/**
* Merge 2 {@link List} {@link Range} together.
* @param r1 {@link List} {@link Range}
* @param r2 {@link List} {@link Range}
* @return {@link List} {@link Range}
*/
private static List> merge(final List> r1,
final List> r2) {
if (!isMergeable(r1, r2)) {
return null;
}
List> l1 = new ArrayList<>();
List> l2 = new ArrayList<>(r2);
for (Range r : r1) {
final Range x = r;
Collection> m = l2.stream()
.filter(rr -> x.isOverlappedBy(rr))
.collect(Collectors.toList());
l2.removeAll(m);
if (m.size() < 2) {
if (m.isEmpty()) {
l1.add(r);
}
for (Range mm : m) {
r = RangeUtil.merge(r, mm);
l1.add(r);
}
} else {
l1 = null;
break;
}
}
if (l1 != null) {
l1.addAll(l2);
}
return l1;
}
/**
* Determines whether {@link List} {@link Range} are mergeable.
* @param r1 {@link List} {@link Range}
* @param r2 {@link List} {@link Range}
* @return boolean
*/
public static boolean isMergeable(final List> r1,
final List> r2) {
boolean merge = false;
if (r1.size() < 2 /*|| r2.size() < 2*/) {
return merge;
}
for (Range r : r1) {
Collection> m = r2.stream()
.filter(rr -> r.isOverlappedBy(rr))
.collect(Collectors.toList());
if (m.size() > 1) {
merge = false;
break;
}
merge = true;
}
if (!merge) {
return false;
}
for (Range r : r2) {
Collection> m = r1.stream()
.filter(rr -> r.isOverlappedBy(rr))
.collect(Collectors.toList());
if (m.size() > 1) {
merge = false;
break;
}
merge = true;
}
return merge;
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy