Java tutorial
/* * Copyright 2014 by Yields. * * 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 io.yields.math.framework.range; import org.apache.commons.lang.Validate; import io.yields.math.framework.Range; import io.yields.math.framework.data.RandomGenerator; public class IntegerRange extends ComparableRange<Integer> { public static Range<Integer> MAX_RANGE_INT = new IntegerRange(Integer.MIN_VALUE, Integer.MAX_VALUE, false, false); public IntegerRange(Integer min, Integer max, boolean minOpen, boolean maxOpen) { super(min, max, minOpen, maxOpen); /** * if interval is ]i, i+1[, then it is empty */ Validate.isTrue(!(min == max - 1 && minOpen && maxOpen), "Interval cannot be empty."); } @Override public Range<Integer> parse(String rangeAsString) { return IntegerRange.fromString(rangeAsString); } @Override public boolean isValid(Integer val) { return super.isValid(val); } @Override protected Integer sampleInternal(RandomGenerator<Integer> randomGenerator) { return randomGenerator.next(); } @Override public Range<Integer> intersect(Range<Integer> that) { boolean newMinOpen = that.getMin() > this.min ? that.isMinOpen() : this.minOpen; boolean newMaxOpen = that.getMax() < this.max ? that.isMaxOpen() : this.maxOpen; return new IntegerRange(Math.max(this.min, that.getMin()), Math.min(this.max, that.getMax()), newMinOpen, newMaxOpen); } public static Range<Integer> fromString(String rangeAsString) { if (rangeAsString.isEmpty()) { return IntegerRange.MAX_RANGE_INT; } else { //lower bound String lowerBoundAsString = rangeAsString.split(",")[0].substring(1); Integer lowerBound = getIntValue(lowerBoundAsString); boolean lowerBoundIsOpen = rangeAsString.charAt(0) == ']'; //upper bound String upperBoundAsString = rangeAsString.split(",")[1]; upperBoundAsString = upperBoundAsString.substring(0, upperBoundAsString.length() - 1); Integer upperBound = getIntValue(upperBoundAsString); boolean upperBoundIsOpen = rangeAsString.charAt(rangeAsString.length() - 1) == '['; return new IntegerRange(lowerBound, upperBound, lowerBoundIsOpen, upperBoundIsOpen); } } private static Integer getIntValue(String value) { if (ComparableRange.NEG_INFTY.equals(value)) { return Integer.MIN_VALUE; } if (ComparableRange.POS_INFTY.equals(value)) { return Integer.MAX_VALUE; } return new Integer(value); } }