Home > Net >  How can I create a java program to find the amount of consecutive numbers in an array?
How can I create a java program to find the amount of consecutive numbers in an array?

Time:12-03

I'm trying to make a Java program to find the number of consecutive numbers in an array. For example, if an array has the values, 1,8,10,4,2,3 there are 4 numbers that are consecutive (1,2,3,4). I've created this program, but I'm getting an error on lines 28 and 31 for ArrayIndexOutOfBoundsException, how do I fix the error? (I'm not even sure if the program I made will work if the errors are fixed). Note: I know there are many solutions online for this but I'm a beginner programmer, and I'm trying to do this a more simple way.

import java.util.Arrays;

class Main {
  public static void main(String[] args) {
    
    consec();
    

  }
    
    static void consec()
    {
            
      int[] nums = {16, 4, 5, 200, 6, 7, 70, 8};
      int counter=0;
      
      Arrays.sort(nums);
      for (int i=0; i < nums.length; i  )
        if (i != nums.length - 1)
          System.out.print(nums[i]   ", ");
        else
          System.out.print(nums[i]);

      for (int i=0; i < nums.length; i  )
        
        for (int j=i; j < nums.length - i; j  )
          if (nums[j   1] - 1 == nums[j])
            counter  ;
          
            else if (nums[j 1]==counter)
              System.out.print("Consective amount is"   counter);
            
   
    }  
}

CodePudding user response:

The issue for the exception lies within the access of nums[j 1]. Note that j can be as large as nums.length - 1 due to the for loop. Thus j 1 can be nums.length which is an OutOfBounds array index.

Secondly I don't think your code solves the task - for example you only print a result if the number of consecutive numbers you've counted appears within the array. However I don't see how these things should correlate. You can solve the problem like this:

for (int i = 1; i < nums.length; i  ) {
  if (nums[i-1] == nums[i] - 1) 
    counter = 2;
  int j = i   1;
  while (j < nums.length && nums[j] - 1 == nums[j-1]) {
    j  ;
    counter  ;
  i = j;
}
System.out.print("Consective amount is"   counter);

Note that the index i starts at 1, thus we can be assured that nums[i-1] exists. If nums has only one element we should not run into any issues as the condition i < nums.length would not be fulfilled. We count two consequitves for every start of a sequence and one addition element for every following consequtive (while loop). When the sequence ends we try finding a new sequence behind it by moving the index i to the end of the last sequence (j = i).

The above code will sum multiple distinct sequences of consequtive numbers. For example the array [17,2,20,18,4,3] has five consequitve numbers (2,3,4 and 17,18)

The algorithm has a time colpexity within O(n) as we either increase i or j by at least on and skip i to j after each sequence.

  • Related