Home > OS >  I want to check a number in array
I want to check a number in array

Time:12-07

i want to check a number in an unordered array and if the number is not included in the array i want to print it and if it is included i dont want to print it, when i tried my code i thought that i could compare the array with an ordered one but it is printing the included numbers not the unincluded numbers what should i do to fix it? (the array should start from 1)

public class Test {

    public static void main(String[] args) {
        //my max number
        int max=5;
        //my unordered array
        int[] A={1,2,3,5};
        
        //creating the ordered array
        int[] B=new int[max];
        int num=1;
        for (int i = 0; i < max; i  ) {
            B[i]=num;
            num  ;
        }
        //checking 
        for (int i = 0; i < A.length; i  ) {
            for (int j = 0; j < B.length; j  ) {
                if (A[i]==B[j]) {
                    System.out.println(B[j]);
                    
                }
            }
        }
    }
        
    
}

CodePudding user response:

A clean way to do this is to convert your input array into a Set and then iterate over all of the numbers you want to check, using the .contains() method to determine if each number is in the Set:

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

public class Test {

    public static void main(String[] args) {
        int max = 5;
        Integer[] A={1,2,3,5};

        Set<Integer> s = new HashSet<>();
        Collections.addAll(s, A);

        for (int i = 1; i <= max; i  )
            if (!s.contains(i))
                System.out.println(i);
    }
}

If you want to avoid the overhead of creating the Set object, you can create a function of your own that does the equivalent of the Set's contains() method on your original array:

public class Test {

    public static boolean contains(Integer[] arr, int x) {
        for (int j = 0; j < arr.length; j  )
            if (arr[j] == x)
                return true;
        return false;
    }

    public static void main(String[] args) {
        int max = 5;
        Integer[] A={1,2,3,5};

        for (int i = 1; i <= max; i  )
            if (!contains(A, i))
                System.out.println(i);
    }
}

The first method will be more efficient (faster) for large arrays, while the second method will be more efficient for small ones.

In either case, the result is:

4

Yet another way would be to sort your array and then do a binary search on the array using Arrays.binarySearch(). This would be particularly attractive if your incoming array was always already sorted.

  • Related