Sam
Sam

Reputation: 405

Java: finding all sequential patterns in list

I have a list of integers which, for example, is {1,2,3,,5,7,8,9}. What I want to do is be able to break that up into {1,2,3} and {7,8,9}. I know of the code

    boolean flag = true;
    for( int i = 0; i < results.size()-1; i++ ) {
        if( results.get(i+1) != results.get(i)+1 ) {
            flag = false;
            break;
        }
    }

but this will only find them starting at the first value (which is not always the case), and will only find one.

Upvotes: 0

Views: 146

Answers (3)

prashant thakre
prashant thakre

Reputation: 5147

Try This,

public void seqList() {
    List<Integer> results= Arrays.asList(1,2,3,5,4,7,8,9,101,102,13,14,15,14,16);

    List<List<Integer>> allSeqList = new ArrayList<>();
    Integer oldVal = null;      
    List<Integer> subList = null;
    Integer lastElement = 1;

    for (Integer value : results) {         
        if (oldVal!=null && value == oldVal + 1) {
            if(subList==null){
                subList= new ArrayList<>();                 
            }
            if(subList.size()==0){
                subList.add(value-1);
            }
            subList.add(value);
        }else{
            if(subList!=null){
                allSeqList.add(subList);
            }

            subList=null;
        }
        if(subList!=null && lastElement==results.size()){
            allSeqList.add(subList);
        }
        lastElement++;
        oldVal=value;
    }

    System.out.println(allSeqList);
}

Upvotes: 2

AmitS
AmitS

Reputation: 180

my method stores the answers in a List<List<Integer>>

ArrayList<List<Integer>> cont = new ArrayList<List<Integer>>();
List<Integer> list = Arrays.asList(1,2,3,5,7,8,9,10,11,13,14,15);
int start = -1;
for(int i = 1;i<list.size();i++){
    if(list.get(i-1)+1 == list.get(i)){
        if(start == -1)
            start = i-1;        
        else if(i==list.size()-1)
            cont.add(list.subList(start,i+1));
    }
    else if(start != -1){
        cont.add(list.subList(start, i));
        start = -1;
    }
}
for(List<Integer> l:cont)
    System.out.println(l);

output:

[1, 2, 3]
[7, 8, 9, 10, 11]
[13, 14, 15]

Upvotes: 0

Rod_Algonquin
Rod_Algonquin

Reputation: 26198

You can manipulate flag and iterate through the array while checking the next array if it is a sequential number prior from the current array.

sample:

int []i = {1,2,3,5,7,8,9,11,12,16,17,18};
    boolean flag = true;
    for(int i2 = 0; i2 < i.length; i2++)
    {
        if(i2+1 < i.length && i[i2+1] == i[i2]+1) {
            System.out.print(i[i2] + " ");
            flag = true;
        }
        else {
            if(flag)
                System.out.print(i[i2]);
            flag = false;
            System.out.println();
        }

result:

1 2 3
7 8 9
11 12
16 17 18

Upvotes: 1

Related Questions