hyperneutrino
hyperneutrino

Reputation: 5425

Java split array into ranges

Using Java, I want to split an array of ints 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

Answers (2)

Suspended
Suspended

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

Suspended
Suspended

Reputation: 1190

You can use

Arrays.copyOfRange(yourArray, inclusiveStartIndex, exclusiveEndIndex);

It returns new array.

Upvotes: 1

Related Questions