Reputation: 5425
Using Java, I want to split an array of int
s into an array of ranges. For example, the array
[1, 2, 3, 4, 5, 6, 7, 8, 100, 101, 102, 103]
would return
[Range(1, 8), Range(100, 103)]
because it consists of 1 to 8 and 100 to 103
It would be best if there were a library, but any sort of method of this conversion is fine.
Upvotes: 1
Views: 3259
Reputation: 1190
Ok James, here's your working solution :)
private void executeTestCode(){
int[] arr = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 100, 101, 102, 103};
Range[] ranges = Arrays.stream(getRanges(arr)).filter(r -> r != null).toArray(Range[]::new);
String output = Arrays.stream(ranges)
.map(Range::toString)
.reduce("[", (dynamicString, stringedRange) -> (dynamicString + stringedRange + ", "));
output = output.substring(0, output.length()-2) + "]";
System.out.println(output);
}
OUTPUT:
[Range(1, 8), Range(100, 103)]
private Range[] getRanges(int[] toBeProcessed){
Range[] result = new Range[toBeProcessed.length]; //larger array won't be needed
int startRange = toBeProcessed[0];
int ranges = 0;
for(int a=0; a<toBeProcessed.length; a++){
try{
if(toBeProcessed[a] + 1 != toBeProcessed[a+1]){
result[ranges] = new Range(startRange, toBeProcessed[a]);
startRange = toBeProcessed[a+1];
ranges++;
}
}catch(ArrayIndexOutOfBoundsException e){
result[ranges] = new Range(startRange, toBeProcessed[toBeProcessed.length-1]);
}
}
return result;
}
CLASS Range:
class Range{
private int start, end;
public Range(int st, int en){
start = st;
end = en;
}
@Override
public String toString(){
return "Range(" +start+ ", " +end+ ")";
}
}
Upvotes: 2
Reputation: 1190
You can use
Arrays.copyOfRange(yourArray, inclusiveStartIndex, exclusiveEndIndex);
It returns new array.
Upvotes: 1