Home > Enterprise >  How to fill in the gaps in each array element?
How to fill in the gaps in each array element?

Time:11-16

If I have an array like this int[] array = {2,4,6,8,11};

how to print the gaps between each array element?

Gaps = 3 5 7 9 10

This is my program but the output is always 5 it doesn't print the other gaps is there any method rather than hash set? thank you

`

import java.util.HashSet;
import java.util.Set;

public class test {
   public static void main(String[] args) {
  int[] array = {2,4,6,8,11};
  
  
  Set<Integer> set = new HashSet<>();
  for(int m : array) {
     if( set.add(m));
  }//for
  for(int i = 1 ; i < set.size() ;i  ) {
   if(!set.contains(i)) {System.out.println("Gaps = "   set.size()); }
  }
   
 }

}

`

CodePudding user response:

In the following solution, I've fixed the logic errors you have made. There are other efficient ways to solve this problem.

import java.util.HashSet;
import java.util.Set;

public class test {
   public static void main(String[] args) {
  int[] array = {2,4,6,8,11};
  Set<Integer> set = new HashSet<>();
  for(int m : array) {
     if( set.add(m));
  }//for
  for(int i = 1 ; i < (2* set.size())   1 ;i  ) {
   if(!set.contains(i)) {System.out.println(i); }
  }
 }
}
  • Related