I am trying to have a union of regular expression and subtraction,I am able work range only like. String regex = "[1-3[5-7]]"; but need different type of numbers with range and at the same time union also like String regex = "\b([1-9]|[1-4][0-9]|5[0-5]&&[191])\b"; In this line am able to match 1 to 55 and also match 191.it is not working.Can any one give the suggestion where the problem getting. I tried for numeric range like below.
public class NumericRangeRegex {
public String baseRange(String num, boolean up, boolean leading1) {
char c = num.charAt(0);
char low = up ? c : leading1 ? '1' : '0';
char high = up ? '9' : c;
if (num.length() == 1)
return charClass(low, high);
String re = c + "(" + baseRange(num.substring(1), up, false) + ")";
if (up) low++; else high--;
if (low <= high)
re += "|" + charClass(low, high) + nDigits(num.length() - 1);
return re;
}
private String charClass(char b, char e) {
return String.format(b==e ? "%c" : e-b>1 ? "[%c-%c]" : "[%c%c]", b, e);
}
private String nDigits(int n) {
return nDigits(n, n);
}
private String nDigits(int n, int m) {
return "[0-9]" + String.format(n==m ? n==1 ? "":"{%d}":"{%d,%d}", n, m);
}
private String eqLengths(String from, String to) {
char fc = from.charAt(0), tc = to.charAt(0);
if (from.length() == 1 && to.length() == 1)
return charClass(fc, tc);
if (fc == tc)
return fc + "("+rangeRegex(from.substring(1), to.substring(1))+")";
String re = fc + "(" + baseRange(from.substring(1), true, false) + ")|"
+ tc + "(" + baseRange(to.substring(1), false, false) + ")";
if (++fc <= --tc)
re += "|" + charClass(fc, tc) + nDigits(from.length() - 1);
return re;
}
private String nonEqLengths(String from, String to) {
String re = baseRange(from,true,false) + "|" + baseRange(to,false,true);
if (to.length() - from.length() > 1)
re += "|[1-9]" + nDigits(from.length(), to.length() - 2);
return re;
}
public String run(int n, int m) {
return "\\b0*?("+ rangeRegex("" + n, "" + m) +")\\b";
}
public String rangeRegex(String n, String m) {
return n.length() == m.length() ? eqLengths(n, m) : nonEqLengths(n, m);
}
}
I think you are on the wrong track. You should simply extract and parse the numeric values and do the calculation in your regular programming language, as recommended by Patrick.
You can still create a wrapper class that helps to check numeric ranges using a simple function like
public static boolean between(int i, int minValueInclusive, int maxValueInclusive) {
return (i >= minValueInclusive && i <= maxValueInclusive);
}
or use commons.lang.Range:
Range<Integer> myRange = Range.between(1, 55);
if (myRange.contains(value)){
// do something
}
Based on conditions Ill try for union and subtraction is `^(?!250)0*?([0-9]|2(5([0-5])|[0-4][0-9])|1[0-9]{2}|[1-9][0-9]|2000)$. In this we are matching 1 to 255 range and 2000 numeric number(union) and for negate 250(subtraction).It's working fine.
Related
I'm trying to implement L-system as functions. For example, dragon curve looks like this:
static String F(int n) {
return n == 0 ? "F" : F(n - 1) + "+" + G(n -1);
}
static String G(int n) {
return n == 0 ? "G" : F(n - 1) + "-" + G(n -1);
}
#Test
void testDragonCurveAsStaticFunction() {
assertEquals("F", F(0));
assertEquals("F+G", F(1));
assertEquals("F+G+F-G", F(2));
assertEquals("F+G+F-G+F+G-F-G", F(3));
}
I want to implement this with lambda functions. I got the following implementation by referring to recursion - Implement recursive lambda function using Java 8 - Stack Overflow.
#Test
void testDragonCurveAsLambdaFunction() {
interface IntStr { String apply(int i); }
IntStr[] f = new IntStr[2];
f[0] = n -> n == 0 ? "F" : f[0].apply(n - 1) + "+" + f[1].apply(n - 1);
f[1] = n -> n == 0 ? "G" : f[0].apply(n - 1) + "-" + f[1].apply(n - 1);
assertEquals("F", f[0].apply(0));
assertEquals("F+G", f[0].apply(1));
assertEquals("F+G+F-G", f[0].apply(2));
assertEquals("F+G+F-G+F+G-F-G", f[0].apply(3));
}
Is there a way to implement this without using an array?
But I want to create a generic L-System, so I don't want to define a new class, interface or method for the dragon curve.
I found a solution that uses Map.
#FunctionalInterface
interface IntStr {
String apply(int n);
static IntStr cond(String then, IntStr... otherwise) {
return n -> n == 0 ? then
: Stream.of(otherwise)
.map(f -> f.apply(n - 1))
.collect(Collectors.joining());
}
static IntStr constant(String string) {
return n -> string;
}
static IntStr call(Map<String, IntStr> map, String functionName) {
return n -> map.get(functionName).apply(n);
}
}
and
#Test
void testDragonCurveAsLambda() {
Map<String, IntStr> map = new HashMap<>();
map.put("F", IntStr.cond("F",
IntStr.call(map, "F"),
IntStr.constant("+"),
IntStr.call(map, "G")));
map.put("G", IntStr.cond("G",
IntStr.call(map, "F"),
IntStr.constant("-"),
IntStr.call(map, "G")));
IntStr f = map.get("F");
assertEquals("F", f.apply(0));
assertEquals("F+G", f.apply(1));
assertEquals("F+G+F-G", f.apply(2));
assertEquals("F+G+F-G+F+G-F-G", f.apply(3));
}
I tried implementing it using a class combining two IntStr fields set via constructor or setters:
interface IntStr {
String apply(Integer i);
}
class Recursive {
IntStr other;
IntStr curr;
public Recursive() {}
public Recursive(String p1, String s1, String p2, String s2) {
this.curr = n -> n == 0 ? p1 : curr.apply(n - 1) + s1 + other.apply(n - 1);
this.other = n -> n == 0 ? p2 : curr.apply(n - 1) + s2 + other.apply(n - 1);
}
public void setCurr(String p, String s) {
this.curr = n -> n == 0 ? p : curr.apply(n - 1) + s + other.apply(n - 1);
}
public void setOther(String p, String s) {
this.other = n -> n == 0 ? p : curr.apply(n - 1) + s + other.apply(n - 1);
}
}
Then the following code succeeded:
void testDragonCurveAsLambdaFunction() {
Recursive f1 = new Recursive("F", "+", "G", "-");
// or using setters
// f1.setCurr("F", "+");
// f1.setOther("G", "-");
assertEquals("F", f1.curr.apply(0));
assertEquals("F+G", f1.curr.apply(1));
assertEquals("F+G+F-G", f1.curr.apply(2));
assertEquals("F+G+F-G+F+G-F-G", f1.curr.apply(3));
}
An example using AtomicReference as a container for IntStr reference without creating Recursive class:
void testDragonCurveAsLambdaFunction() {
AtomicReference<IntStr>
curr = new AtomicReference<>(),
other = new AtomicReference<>();
curr.set(n -> n == 0 ? "F" : curr.get().apply(n - 1) + "+" + other.get().apply(n - 1));
other.set(n -> n == 0 ? "G" : curr.get().apply(n - 1) + "-" + other.get().apply(n - 1));
assertEquals("F", curr.get().apply(0));
assertEquals("F+G", curr.get().apply(1));
assertEquals("F+G+F-G", curr.get().apply(2));
assertEquals("F+G+F-G+F+G-F-G", curr.get().apply(3));
}
How to validate bank routing number in java ?
can any one help me out.
for example
void boolean validate(String str){
// some code
return true; //if valid otherwise return false
}
Please find who needs a routing number validator.
routing-number.validator.ts
import { AbstractControl, ValidationErrors } from '#angular/forms';
export const routingNumberValidator = (): ((AbstractControl) => ValidationErrors | null) => {
return (control: AbstractControl): ValidationErrors | null => {
const targetValue = control.value;
if (!targetValue) {
return null;
}
const digits = targetValue.split('').map(d => parseInt(d, 10));
const checksum = 3 * (digits[0] + digits[3] + digits[6]) + 7 * (digits[1] + digits[4] + digits[7]) + (digits[2] + digits[5] + digits[8]);
return (checksum % 10 === 0) ? null : { routingnumber: true };
};
};
In your yourComponent.component.ts:
this.yourForm = this.fb.group({
routingNumber: [null, Validators.compose([
Validators.required,
routingNumberValidator()
])]
});
And in your yourComponent.component.html:
<nz-form-control [nzErrorTip]="routingNumberErrorTemplate">
<input
nz-input
formControlName="routingNumber"
id="routingNumber">
</nz-form-control>
<ng-template
#routingNumberErrorTemplate
let-control>
<span data-cy="routing-number-input-error">
<ng-container *ngIf="control.hasError('required')">The routing number is required</ng-container>
<ng-container *ngIf="control.hasError('routingnumber')">The routing number is invalid</ng-container>
</span>
</ng-template>
I got the solution. Bank Routing Number is validate by using this simple method.
public boolean validateRoutingNumber(String s) {
int checksum=0, len=0, sum=0, mod = 0;
len = s.length();
if(len != 9){
return false;
}else {
String newString = s.substring(s.length()-1);
checksum = Integer.parseInt(newString);
sum = (7*(Integer.parseInt(""+s.charAt(0))+Integer.parseInt(""+s.charAt(3))+ Integer.parseInt(""+s.charAt(6)))) +
(3*(Integer.parseInt(""+s.charAt(1))+Integer.parseInt(""+s.charAt(4))+ Integer.parseInt(""+s.charAt(7))))+
(9*(Integer.parseInt(""+s.charAt(2))+Integer.parseInt(""+s.charAt(5))));
mod = sum % 10;
if(mod == checksum)
return true;
else
return false;
}
}
Just for fun, I wrote a Angular js directive for doing this same thing:
angular.module('ldPortal.directives')
.directive('routingnumber', function(){
return {
// only use as an attribute
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attr, ctrl){
var regex = new RegExp('^[0-9]{9}$','');
var num_at = function(str, index){
try {
return parseInt(str.charAt(index))
}catch (execption){
console.write(execption);
}
};
var validate = function(value){
if(! (value)){
return false;
}
var strVal = value.toString();
if (!regex.test(strVal)){
return false;
}
var checksum = parseInt(strVal.substr(strVal.length-1));
var sum = 0;
sum += 7 * (num_at(strVal, 0)+num_at(strVal, 3)+num_at(strVal,6));
sum += 3 * (num_at(strVal, 1)+num_at(strVal, 4)+num_at(strVal, 7));
sum += 9 * (num_at(strVal, 2)+num_at(strVal, 5));
var mod = sum % 10;
return checksum == mod;
};
ctrl.$parsers.push(function(value){
var is_valid = validate(value);
ctrl.$setValidity('routingnumber', is_valid);
return is_valid ? value : undefined;
});
ctrl.$formatters.push(function(value){
var is_valid = validate(value);
ctrl.$setValidity('routingnumber', is_valid);
return value;
});
}
};
});
I created a simple Routing Validator, hope this works.
RoutingNumberValidator:
import static java.lang.Character.getNumericValue;
public static class RoutingNumberValidator {
public boolean isValid(String value) {
boolean isValid = value != null && value.matches("[0-9]{9}");
if (isValid) {
int check = 0;
for ( int index = 0; index < 3; index++ ) {
int pos = index * 3;
check += getNumericValue(value.charAt(pos)) * 3;
check += getNumericValue(value.charAt(pos + 1)) * 7;
check += getNumericValue(value.charAt(pos + 2));
}
isValid = check != 0 && check % 10 == 0;
}
return isValid;
}
}
RoutingNumberValidatorTest:
public class RoutingNumberValidatorTest {
private List<String> validRoutingNumbers = Arrays.asList("122105155", "082000549");
private List<String> invalidRoutingNumbers = Arrays.asList("1232101155", "032000549");
#Test
public void isValid() throws Exception {
RoutingNumberValidator routingNumberValidator = new RoutingNumberValidator();
validRoutingNumbers.forEach(it-> assertThat(routingNumberValidator.isValid(it)).as("Invalid Routing Number should not be valid %s", it).isTrue());
invalidRoutingNumbers.forEach(it-> assertThat(routingNumberValidator.isValid(it)).as("Invalid Routing Number should not be valid %s", it).isFalse());
}
}
I know this question is old and is already answered many times, but this answer from BrainJar is quite concise and works perfectly. So I thought I'd share.
validateRoutingNumber(num: string) {
// Run through each digit and calculate the total.
let n = 0;
for (let i = 0; i < num.length; i += 3) {
n += parseInt(num.charAt(i), 10) * 3
+ parseInt(num.charAt(i + 1), 10) * 7
+ parseInt(num.charAt(i + 2), 10);
}
// If the resulting sum is an even multiple of ten (but not zero),
// the aba routing number is good.
if (n != 0 && n % 10 == 0) {
return true;
} else {
return false;
}
}
and here is for python:
def validate_routing_number(routing_number):
# quick easy validations
if routing_number is None or routing_number == '':
return False
invalid_routing_message = 'invalid routing number'
if not re.match(r'^[0-9]{9}$', routing_number):
return False
# here is the more complicated validation!
checksum = int(routing_number[-1]) # last digit
sum = 0 # http://en.wikipedia.org/wiki/Routing_transit_number
sum += 7 * (int(routing_number[0])+int(routing_number[3])+int(routing_number[6]))
sum += 3 * (int(routing_number[1])+int(routing_number[4])+int(routing_number[7]))
sum += 9 * (int(routing_number[2])+int(routing_number[5]))
mod = sum % 10
return checksum != mod
package RoutingNumberAlgo;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int checksum = 0, len = 0, sum = 0, mod = 0, rem = 0;
Scanner ss = new Scanner(System.in);
System.out.print("Enter the Routing Number: ");
String s = ss.nextLine();
len = s.length();
if (len != 9) {
System.out.print("Length not 9");
} else {
String newString = s.substring(s.length() - 1);
checksum = Integer.parseInt(newString);
sum = (3 * (Integer.parseInt("" + s.charAt(0)))) + (7 * (Integer.parseInt("" + s.charAt(1))))
+ (1 * (Integer.parseInt("" + s.charAt(2)))) + (3 * (Integer.parseInt("" + s.charAt(3))))
+ (7 * (Integer.parseInt("" + s.charAt(4)))) + (1 * (Integer.parseInt("" + s.charAt(5))))
+ (3 * (Integer.parseInt("" + s.charAt(6)))) + (7 * (Integer.parseInt("" + s.charAt(7))));
mod = 10 - (sum % 10);
if (mod == checksum)
System.out.print("True");
else
System.out.print("False");
;
}
}
}
( I'm beginner )
double x = 0.5;
double y = 0.3;
String[]normal = {"x","y","cos","sin","avg"};
String[]complex = {"cos","sin","avg"};
char coordinate = (char) (new Random().nextInt(2) + 'x');
String result = "";
if(levels == 1){
String value1 = (normal[new Random().nextInt(normal.length)]);
if (value1.equals("sin") ||value1.equals("cos")){
result = value1 + "( pi *" + coordinate + ")";
}
else if(value1.equals("avg")){
result = value1 + "(" + coordinate + "," + coordinate + ")" ;
}
else{
result = value1 ;
}
}else{
String value = (complex[new Random().nextInt(complex.length)]);
if((value.equals("sin") ||value.equals("cos"))&&levels!=0 ){
result = value + "( pi *" + createFunction(levels - 1) + ")";
}
else if(value.equals("avg")&& levels !=0){
result = value +"(" + createFunction (levels - (levels-1)) + "," + createFunction (levels - (levels-1)) + ")" ;
}
else if(value.equals("avg")&& levels ==2){
result = value + "(" + createFunction (levels - 1) + "," + coordinate + ")" ;
}
else{
result = value ;
}
}
return result;
}
double functions = ....................... ;
result will be "sin(pi*cos(pi*x*y))" in String
how to calculate this string and keep in double functions
You are asking how to parse a string containing an arbitrary expression and then evaluate it to get a floating-point result.
That is quite difficult, requiring an expression parser, to convert the string into an expression tree, and an expression tree evaluator, to actually calculate the result.
You can do this using Groovy scripts. The trick is to evaluate your input as a Java-like expression:
public final class Test{
private static GroovyShell createMathShell() {
GroovyShell shell = new GroovyShell();
shell.evaluate("" +
"cos = {double x -> Math.cos(x)}\n" + // predefine functions as lambda
"sin = {double x -> Math.sin(x)}\n" + // expressions
"pi = Math.PI\n" // define pi
);
return shell;
}
public static void main(String[] args) {
GroovyShell shell = createMathShell();
// set values
shell.setVariable("x", 0);
shell.setVariable("y", 1);
// evaluate
double result = (Double) shell.evaluate("sin(pi*cos(pi*x*y))");
System.out.println(result);
}
}
Executing this code will print:
1.2246467991473532E-16
It would be wise to initialise a double and directly write the value into that variable.
Double answer = ....;
When you need the original value, just use the variable answer. When you need it as a string, just use:
String answer_string = String.valueOf(answer);
Or, for example:
System.out.println(String.valueOf(answer));
Math.sin and Math.cos methods will accept double values, and return a double. Simply write a method taking as arguments x and y to return the formula:
double myAlgorithm( double x, double y){
return Math.sin(Math.PI*Math.cos(Math.PI*x*y))
}
This will work passing x and y as int as it will be casted implicitly to double
double myAlgorithm( int x, int y){
return Math.sin(Math.PI*Math.cos(Math.PI*x*y))
}
And, if you want to pass Strings instead of types:
double myAlgorithm( String x, String y){
return Math.sin(Math.PI*Math.cos(Math.PI*(Double.parseDouble(x).doubleValue())*(Double.parseDouble(y).doubleValue())))
}
This should do it:
Double.valueOf(string);
I am creating a table of contents, and what I have is a Map of product numbers to pages. So an entry might look like this:
ABC123 => [59, 58, 57, 19, 36, 15, 33, 34, 13, 39, 11, 37, 38, 21, 20, 40, 63, 60, 45, 46, 22, 23, 24, 26, 3, 2, 10, 1, 7, 6, 5, 4, 8]
What I want to get from this is:
1-8,10,11,13,15,19-24,26,33,34,36-38,40,45,46,57-60
I can code this of course, but I figured that someone else has already solved this problem. My Googling has yielded naught.
I appreciate any help you can offer, as always!
You could collect the numbers into a sorted set and then iterate over the numbers.
Quick and dirty example:
SortedSet<Integer> numbers = new TreeSet<Integer>();
numbers.add( 1 );
numbers.add( 2 );
numbers.add( 3 );
numbers.add( 6 );
numbers.add( 7 );
numbers.add( 10 );
Integer start = null;
Integer end = null;
for( Integer num : numbers ) {
//initialize
if( start == null || end == null ) {
start = num;
end = num;
}
//next number in range
else if( end.equals( num - 1 ) ) {
end = num;
}
//there's a gap
else {
//range length 1
if( start.equals( end )) {
System.out.print(start + ",");
}
//range length 2
else if ( start.equals( end - 1 )) {
System.out.print(start + "," + end + ",");
}
//range lenth 2+
else {
System.out.print(start + "-" + end + ",");
}
start = num;
end = num;
}
}
if( start.equals( end )) {
System.out.print(start);
}
else if ( start.equals( end - 1 )) {
System.out.print(start + "," + end );
}
else {
System.out.print(start + "-" + end);
}
Yields: 1-3,6,7,10
Apache Commons has the IntRange type that you can use. Unfortunately I didn't find a good corresponding set of utilities to create them. Here's the basic approach you could use:
//create a list of 1-integer ranges
List<IntRange> ranges = new LinkedList<IntRange>();
for ( int pageNum : pageNums ) {
ranges.add(new IntRange(pageNum));
}
//sort the ranges
Collections.sort(ranges, new Comparator<IntRange>() {
public int compare(IntRange a, IntRange b) {
return Integer.valueOf(a.getMinimumInteger()).compareTo(b.getMinimumInteger());
}
});
List<IntRange> output = new ArrayList<IntRange>();
if ( ranges.isEmpty() ) {
return output;
}
//collapse consecutive ranges
IntRange range = ranges.remove(0);
while ( !ranges.isEmpty() ) {
IntRange nextRange = ranges.remove(0);
if ( range.getMaximumInteger() == nextRange.getMinimumInteger() - 1 ) {
range = new IntRange(range.getMinimumInteger(), nextRange.getMaximumInteger());
} else {
output.add(range);
range = nextRange;
}
}
output.add(range);
Alternatively you could skip the first step and create the ranges directly from the sorted list of page numbers.
Edit: A better description:
I had to deal with something similar to support a sorted collection of finite ranges, I used a mix of Google's Guava Range class and binary search to insert the element at the corresponding range or create a new singleton Range (A range with 1 element), eventually with more inserts the ranges have chances of expanding (Or shrinking/splitting in case of removal), removal is pretty fast because locating the corresponding range where the element is uses a binary search:
import com.google.common.collect.DiscreteDomains;
import com.google.common.collect.Lists;
import com.google.common.collect.Range;
import com.google.common.collect.Ranges;
import java.util.Collection;
import java.util.List;
public class IntRangeCollection
{
private int factor=10;
private List<Range<Integer>> rangeList=null;
public IntRangeCollection()
{
rangeList=Lists.newArrayListWithExpectedSize(1000);
}
public IntRangeCollection(final int size)
{
rangeList=Lists.newArrayListWithExpectedSize(size);
}
public IntRangeCollection(final int size, final int factor)
{
rangeList=Lists.newArrayListWithExpectedSize(size);
this.factor=factor;
}
protected IntRangeCollection(final List<Range<Integer>> rangeList)
{
this.rangeList=rangeList;
}
public static IntRangeCollection buildIntRangesCollectionFromArrays(final List<Integer[]> arrays)
{
final List<Range<Integer>> rangeList=Lists.newArrayListWithCapacity(arrays.size());
for(Integer[] range : arrays){
rangeList.add(range.length == 1 ? Ranges.singleton(range[0]) : Ranges.closed(range[0], range[1]));
}
return new IntRangeCollection(rangeList);
}
public boolean addElements(final Collection<Integer> elements)
{
boolean modified=false;
for(Integer element : elements){
modified=addElement(element) || modified;
}
return modified;
}
public boolean removeElements(final Collection<Integer> elements)
{
boolean modified=false;
for(Integer element : elements){
modified=removeElement(element) || modified;
}
return modified;
}
public boolean addElement(final Integer element)
{
final Range<Integer> elementRange=Ranges.singleton(element);
if(rangeList.isEmpty()){
rangeList.add(elementRange);
} else{
int
start=0, mid=0,
end=rangeList.size() - 1;
Range<Integer> midRange=null;
while(start<=end){
mid=(start + end) / 2;
midRange=rangeList.get(mid);
if(midRange.contains(element)){
return false;
} else if(testLinkable(midRange, element)){
rangeList.set(mid, midRange.span(elementRange));
if(mid>0){
final Range<Integer> a=rangeList.get(mid - 1);
if(testLinkable(a, midRange)){
rangeList.set(mid - 1, a.span(midRange));
rangeList.remove(mid);
mid--;
}
}
if(mid<rangeList.size() - 1){
final Range<Integer> b=rangeList.get(mid + 1);
if(testLinkable(midRange, b)){
rangeList.set(mid, midRange.span(b));
rangeList.remove(mid + 1);
}
}
return true;
} else if(midRange.lowerEndpoint().compareTo(element)<0){
start=mid + 1;
} else{
end=mid - 1;
}
}
//noinspection ConstantConditions
rangeList.add(midRange.lowerEndpoint().compareTo(element)<0 ? mid + 1 : mid, elementRange);
}
return true;
}
public boolean removeElement(final Integer element)
{
final Range<Integer> elementRange=Ranges.singleton(element);
if(rangeList.isEmpty()){
rangeList.add(elementRange);
} else{
int
start=0, mid,
end=rangeList.size() - 1;
while(start<=end){
mid=(start + end) / 2;
final Range<Integer> midRange=rangeList.get(mid);
if(midRange.contains(element)){
final Integer
lower=midRange.lowerEndpoint(),
upper=midRange.upperEndpoint();
if(lower.equals(upper)){
rangeList.remove(mid);
} else if(lower.equals(element)){
rangeList.set(mid, Ranges.closed(element + 1, upper));
} else if(upper.equals(element)){
rangeList.set(mid, Ranges.closed(lower, element - 1));
} else{
rangeList.set(mid, Ranges.closed(element + 1, upper));
rangeList.add(mid, Ranges.closed(lower, element - 1));
}
return true;
} else if(midRange.lowerEndpoint().compareTo(element)<0){
start=mid + 1;
} else{
end=mid - 1;
}
}
}
return false;
}
public List<Integer> getElementsAsList()
{
final List<Integer> result=Lists.newArrayListWithExpectedSize(rangeList.size() * factor);
for(Range<Integer> range : rangeList){
result.addAll(range.asSet(DiscreteDomains.integers()));
}
return result;
}
public List<Integer[]> getRangesAsArray()
{
final List<Integer[]> result=Lists.newArrayListWithCapacity(rangeList.size());
for(Range<Integer> range : rangeList){
final Integer
lower=range.lowerEndpoint(),
upper=range.upperEndpoint();
result.add(lower.equals(upper) ? new Integer[]{lower} : new Integer[]{lower,upper});
}
return result;
}
public int getRangesCount()
{
return rangeList.size();
}
private boolean testLinkable(final Range<Integer> range, final Integer element)
{
return Ranges.closed(range.lowerEndpoint() - 1, range.upperEndpoint() + 1).contains(element);
}
private boolean testLinkable(final Range<Integer> a, final Range<Integer> b)
{
return Ranges.closed(a.lowerEndpoint() - 1, a.upperEndpoint() + 1).isConnected(b);
}
#Override
public String toString()
{
return "IntRangeCollection{" +
"rangeList=" + rangeList +
'}';
}
public static void main(String[] args)
{
final int MAX_NUMBER=1000;
final long startMillis=System.currentTimeMillis();
final IntRangeCollection ranges=new IntRangeCollection();
for(int i=0; i<MAX_NUMBER; i++){
//noinspection UnsecureRandomNumberGeneration
ranges.addElement((int) (Math.random() * MAX_NUMBER));
}
System.out.println(MAX_NUMBER + " contained in " + ranges.rangeList.size() + " ranges done in " + (System.currentTimeMillis() - startMillis) + "ms");
System.out.println(ranges);
for(int i=0; i<MAX_NUMBER / 4; i++){
//noinspection UnsecureRandomNumberGeneration
ranges.removeElement((int) (Math.random() * MAX_NUMBER));
}
System.out.println(MAX_NUMBER + " contained in " + ranges.rangeList.size() + " ranges done in " + (System.currentTimeMillis() - startMillis) + "ms");
System.out.println(ranges);
}
}
You can use Arrays.sort() and find neighbouring duplicates/ranges. However I suspect TreeSet may be simpler to use.
This is a good example, it shows a simple way to accomplish this.
I have a method that generates and error that a int was expected but found boolean but when I switch it to a boolean it says the same error but reverse int and boolean. Here is my code:
private void compileDeclaration(boolean isGlobal) {
if (equals(theToken, "int")) {
accept("int");
String ident = theToken;
if (!isIdent(theToken)) t.error("expected identifier, got " + theToken);
else if (isGlobal){
symTable.allocVar(ident, isGlobal);
}
if (!isGlobal) cs.emit(Machine.ALLOC, symTable.stackFrameSize());
//dprint("declaring int " + ident);
theToken = t.token();
accept (";");
} else if (equals (theToken, "final")) {
accept("final");
accept("int");
String ident = theToken;
if (!isIdent(theToken)) t.error("expected identifier, got " + theToken);
theToken = t.token();
accept("=");
int numvalue = new Integer(theToken).intValue();
if (!isNumber(theToken)) t.error("expected number, got " + theToken);
else if (numvalue = 0) { **//This is where it highlights my error**
symTable.allocConst(ident, numvalue);
}
Any help would be most appreciated.
The line
else if (numvalue = 0) { **//This is where it highlights my error**
is missing an equals symbol, i.e.
else if (numvalue == 0) { **//This is where it highlights my error**
Most likely you're calling it in two different places, once with an integer and once with a boolean.
Either that or symTable.allocVar() expects an int.