Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fill in the gaps in each array element?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()); }
  }
   
 }

}

`

>Solution :

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); }
  }
 }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading