11

I have a list of integers placed in order. I want to get groups of consecutive integers as arrays with 1st and last integer of each group.

For example, for (2,3,4,5,8,10,11,12,15,16,17,18,25) I want to get a list with those arrays: [2,5] [8,8] [10,12] [15,18] [25,25]

Here is my code:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class MyRangesTest {


public static void main(String[] args) {
    //create list of integers
    List<Integer> list=Arrays.asList(2,3,4,5,8,10,11,12,15,16,17,18,25);
    System.out.println("list:" + list);


        //create a list with integers where a new sequense of consecutive integers starts or ends
        List<Integer> sublistsStarsAndEnds= new ArrayList<>();
        sublistsStarsAndEnds.add(list.get(0));//1st line (always in sublistsStarsAndEnds list)
        for (int i=1; i<list.size()-1; i++){
            if (list.get(i)>1+list.get(i-1)){
                sublistsStarsAndEnds.add(list.get(i-1));
                sublistsStarsAndEnds.add(list.get(i));
            }
        }
        sublistsStarsAndEnds.add(list.get(list.size()-1));//last line (always in sublistsStarsAndEnds list)
        System.out.println("sublistsStarsAndEnds: " + sublistsStarsAndEnds);//present the result


        //create list with arrays that represents start and end of each subrange of consequent integers
        List<Integer[]> ranges= new ArrayList<>();
        for (int i=0; i<sublistsStarsAndEnds.size()-1; i=i+2){
            Integer[] currentrange=new Integer[2];
            currentrange[0]=sublistsStarsAndEnds.get(i);
            currentrange[1]=sublistsStarsAndEnds.get(i+1);
            ranges.add(currentrange);//present the result
        }

        //present the result
        String rangestxt="";//create result text
        for (int i=0; i<ranges.size(); i++){
            rangestxt=rangestxt+ranges.get(i)[0]+ " " + ranges.get(i)[1]+ "    ";
         }        
        System.out.println("ranges: " + rangestxt);//present the result


    }

}

This code works in the general case for what I want but when the last sequence has only 1 integer it fails to get the right result.

For example when using this list: (2,3,4,5,8,10,11,12,15,16,17,18,25) instead of getting the ranges [2,5] [8,8] [10,12] [15,18] [25,25] we get the ranges [2,5] [8,8] [10,12] [15,25].

The problem is with the detection of where the ranges start or end. In my code those places are stored in the sublistsStarsAndEnds list. Here instead of getting [2, 5, 8, 8, 10, 12, 15, 15, 25, 25] we get [2, 5, 8, 8, 10, 12, 15, 25]. I tried to correct the code but I without good results.

Any suggestions please?

P.S. Someone wanted to get the result I want and asked a question for Python here "Identify groups of continuous numbers in a list But I don't know Python so I tried my own coding.

Community
  • 1
  • 1
geo
  • 517
  • 1
  • 9
  • 28

6 Answers6

9

try this

 public static void main(String[] args) {
    List<Integer> list=Arrays.asList(2,3,4,5,8,10,11,12,15,16,17,18,19,25);
    List<List<Integer>>lList=new ArrayList<List<Integer>>(); //list of list of integer
    System.out.println("list:" + list);
    int i=0;
    int start=0;
        List<Integer> sList=new ArrayList<Integer>(2);
        for(  i = 1; i <list.size();i++){

           if( list.get(i - 1) + 1 != list.get(i)){
               sList.add(list.get(start));
               sList.add(list.get(i-1));
               lList.add(sList);
               sList=new ArrayList<Integer>(2);
               start=i;

            }

        }
        sList.add(list.get(start));        // for last range
        sList.add(list.get(list.size()-1));
        lList.add(sList);


    System.out.println("Range :"+lList);
}

output :

list:[2, 3, 4, 5, 8, 10, 11, 12, 15, 16, 17, 18, 19, 25]
Range :[[2, 5], [8, 8], [10, 12], [15, 19], [25, 25]]
Rustam
  • 6,485
  • 1
  • 25
  • 25
5

If I understand your question, you could write a POJO class Range like

static class Range {
    private int start;
    private int end;

    Range(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    public String toString() {
        return String.format("%d - %d", start, end);
    }
}

Then your problem becomes adding a start to an end position where the end position is i-1 in list.get(i - 1) + 1 != list.get(i). Something like,

public static void main(String[] args) {
    List<Integer> list = Arrays.asList(2, 3, 4, 5, 8, 10, 11, 12, 15, 16,
            17, 18, 25);
    System.out.println("list:" + list);
    int start = 0;
    List<Range> ranges = new ArrayList<>();
    for (int i = 1; i < list.size(); i++) {
        if (list.get(i - 1) + 1 != list.get(i)) {
            ranges.add(new Range(list.get(start), list.get(i - 1)));
            start = i;
        }
    }
    ranges.add(new Range(list.get(start), list.get(list.size() - 1)));
    System.out.println(ranges);
}

Output is (as requested)

[2 - 5, 8 - 8, 10 - 12, 15 - 18, 25 - 25]

I will point out that this is very nearly Run-length Encoding.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
2

Elegant Solution:

    static String pair(int[] array){
        String res = "";
        
        int i = 0, j = 1;
        //loop through all items in array.
        while(i < array.length){
            //increase j while array[j] - array[j - 1] equals 1
            while(j < array.length && array[j] - array[j - 1] == 1){
                j++;
            }
            //we came out of that loop, no longer in a sequence. 
            //write to the output.
            res += toTuple(i,j - 1, array);
            //i now points to j.
            //j is now i + 1;
            i = j;
            j = i + 1;
        }
    
        return res;
    }
    
    static String toTuple(int low, int high, int[] array){
        return "[" + array[low] + "," + array[high] + "]";
    }
  • Sample Input: {1, 2, 3, 6, 7,9,10,11,13,14,15,20}
  • Output: [1,3][6,7][9,11][13,15][20,20]
Rafael Valle
  • 151
  • 2
  • 9
1

Another short answer in kotlin, Assuming no repetition in the list

    list.fold(mutableListOf<MutableList<Int>>()) { acc, i ->
        acc.also { outer ->
            outer.lastOrNull()?.takeIf { it[1] + 1 == i  }?.also {
                it[1] = i
            } ?: mutableListOf(i, i).also {
                outer.add(it)
            }
        }
    }
jfawkes
  • 396
  • 1
  • 7
0

Here's a simple little algorithm that I sometimes adapt and use.

public void printRanges(int[] input) {
    if (input.length == 0)
        return;

    // Only necessary if not already sorted
    Arrays.sort(input);

    int start = input[0];
    int end = input[0];

    for (int rev : input) {
        if (rev - end > 1) {
            // break in range
            System.out.println("Range: [" + start + ", " + end + "]");
            start = rev;
        }
        end = rev;
    }
    System.out.println("Range: [" + start + ", " + end+"]");
}
triadiktyo
  • 479
  • 2
  • 9
0

I'd like to contribute a solution written in kotlin:

@Test
fun test_extract_continuous_range() {
    val inputList = listOf(0, 2, 3, 4, 5, 8, 10, 11, 12, 15, 16, 17, 18, 19, 25, 26, 27, 30)
    println("Input:  $inputList")

    val result = mutableListOf<IntRange>()
    result.add(inputList.first()..inputList.first()) // add the first item as the first range
    inputList.windowed(2)
        .map { w -> w.first() to w.second() } // optional map to Pair for convenient
        .forEach { p ->
            if (p.first + 1 == p.second) {
                // same range, extend it
                val updatedLastRange = result.last().start..p.second
                result[result.lastIndex] = updatedLastRange
            } else {
                // new range
                result.add(p.second..p.second)
            }
        }

    println("Result: $result")

    val sizes = result.map(IntRange::count)
    println("Sizes:  $sizes")
}
Hoang Tran
  • 481
  • 1
  • 7
  • 13