Reputation: 1
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!!!
Upvotes: 0
Views: 1930
Reputation: 5331
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");
Upvotes: 2
Reputation: 7917
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);
Upvotes: 0
Reputation: 521093
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
Upvotes: 0