0

I want to check if numbers in an arraylist are sequential. The number in array start with 1, and for the next should be 2, 3, and 4. This means that every next element is 1 larger than the previous.

public static void main(String[]args){
    ArrayList<Integer> array = new ArrayList<Integer>();
    array.add(1); array.add(3);
    for (int i = 0; i < array.size(); i++){
        if(logic here){
            System.out.println(not sequence);
        }else{
            system.out.pritnln(sequence);
        }
    }
}

For this case, after 1 it should be 2, but there is 3. how can i implement the correct logic for this case? Thank you!!!

Jason
  • 11,744
  • 3
  • 42
  • 46

3 Answers3

2

You can try:

Scanner sc = new Scanner(System.in);
System.out.print("Enter number of elements: ");
int input = sc.nextInt();
List<Integer> al = new ArrayList<Integer>();
            
// Store elements into arraylist
for(int i=0; i<input; i++)
    al.add(sc.nextInt());
            
boolean isSequential = IntStream.range(1, al.size()).allMatch(value -> al.get(value) - al.get(value - 1) == 1);
System.out.println(isSequential ? "Sequential" : "Not Sequential");
Nitin Bisht
  • 5,053
  • 4
  • 14
  • 26
0

You could just walk down the array once, checking for a delta of some value other than 1:

List<Integer> list = Arrays.asList(new Integer[] {1, 2, 3, 5});
for (int i=1; i < list.size(); ++i) {
    if (list.get(i) - list.get(i-1) != 1) {
        System.out.println("out of sequence");
        break;
    }
}

This prints:

1
2
3
out of sequence
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • for this case, you already have element in an arraylist. what if the elements in the array are obtained from user input? in case arraylist is empty, and when user input some number, the number will stored in arraylist. Thank you for your answer :) – rizki tamin Feb 27 '20 at 04:25
  • Store user input in two variables and apply the same logic mentioned here. – R0b1n Feb 27 '20 at 04:28
0

Simple one-liner, you can use an IntStream range to match the elements:

List<Integer> list = List.of(1, 2, 3);
boolean isSequential = IntStream.range(0, list.size())
        .allMatch(value -> value + 1 == list.get(value));
System.out.println(isSequential);
Kartik
  • 7,677
  • 4
  • 28
  • 50