import com.google.common.collect.Lists;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.collections.CollectionUtils;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* 功能描述: 用于表达连续的整数区间
*
* @author : yuanchao.he
* @version 1.0 2017-04-06
*/
@Getter
@Setter
public class LocalRange implements Serializable {
private int lowerRange;
private int upperRange;
public LocalRange(int lowerRange, int upperRange) throws Exception {
if (lowerRange > upperRange) {
throw new Exception(
"invalid range number, upperRange must greater or equal to lowerRange");
}
this.lowerRange = lowerRange;
this.upperRange = upperRange;
}
private LocalRange() {}
/**
* 单个区间内是否包含特定的整数
* @param current
* @return
*/
public boolean contains(final int number) {
return this.lowerRange <= number && number <= this.upperRange;
}
/**
* 一组区间内是否包含特定的整数
* @param ranges
* @param number
* @return
*/
public static boolean contains(final List ranges, final int number){
return binarySearch(ranges, number)!=null;
}
/**
* 采用二分查找的方式来查询
* @param ranges
* @param number
* @return
*/
public static LocalRange binarySearch(List ranges, int number) {
if (CollectionUtils.isEmpty(ranges)) {
return null;
}
int from = 0;
int to = ranges.size() - 1;
while (from <= to) {
int middle = (to - from) / 2 + from;
if (ranges.get(middle).contains(number)) {
return ranges.get(middle);
}
if (ranges.get(middle).getUpperRange() < number) {
from = middle + 1;
}
if (ranges.get(middle).getLowerRange() > number) {
to = middle - 1;
}
}
return null;
}
/**
* 将集合中的整数转化为一组区间
* @param collection
* @return
*/
public static List fromCollection(Collection collection) {
if (CollectionUtils.isEmpty(collection)) {
return Collections.emptyList();
}
List numbers = Lists.newArrayList(collection);
Collections.sort(numbers);
List ranges = Lists.newArrayList();
int lowerRange = numbers.get(0);
int upperRange = numbers.get(0);
for (int index = 1; index < numbers.size(); index++) {
if ((upperRange + 1) == numbers.get(index)) {
upperRange = numbers.get(index);
} else {
ranges.add(LocalRange.init(lowerRange, upperRange));
lowerRange = numbers.get(index);
upperRange = lowerRange;
}
}
ranges.add(LocalRange.init(lowerRange, upperRange));
return ranges;
}
private static LocalRange init(int lowerRange, int upperRange) {
LocalRange localRange = new LocalRange();
localRange.lowerRange = lowerRange;
localRange.upperRange = upperRange;
return localRange;
}
}