Write a method called is Unique that accepts an array of int

Write a method called is Unique that accepts an array of integers as a parameter and returns a boolean value indicating whether or not the values in the array are unique (true for yes, false for no). The values in the list are considered unique if there is no pair of values that are equal. For example, if passed an array containing {3, 8, 12, 2, 9, 17, 43, -8, 46), your method should return true, but if passed (4, 7, 3, 9, 12, -47, 3, 74), your method should return false because the value 3 appears twice.

Solution

Method:

private static boolean isUnique(int[] arr) {
       //Declaring variable
       int count = 0;

       /* This for loop will check whether the array
       * elements contains Duplicates or not
       */
       for (int i = 0; i < arr.length; i++) {
           for (int j = 0; j < arr.length; j++) {
               if (arr[i] == arr[j]) {
                   count++;
               }
           }

       }
       /* Count is equal to length of the array
       * means no duplicates in the array
       */
       if(count==arr.length)
       return true;
       else
return false;
      
   }

_____________________

Complete program to make you Understood:

package org.students;

public class Demo {

   public static void main(String[] args) {
       int arr1[] = { 3, 8, 12, 2, 9, 17, 43, -8, -46 };
       int arr2[] = { 4, 7, 3, 9, 12, -47, 3, 74 };

       boolean bool = isUnique(arr1);
       if (bool)
           System.out.println(\"Elements in Array1 are unique\");
       else
           System.out.println(\"Elements in Array1 are not unique\");

       boolean bool1 = isUnique(arr2);
       if (bool1)
           System.out.println(\"Elements in Array2 are unique\");
       else
           System.out.println(\"Elements in Array2 are not unique\");

   }

   private static boolean isUnique(int[] arr) {
       //Declaring variable
       int count = 0;

       /* This for loop will check whether the array
       * elements contains Duplicates or not
       */
       for (int i = 0; i < arr.length; i++) {
           for (int j = 0; j < arr.length; j++) {
               if (arr[i] == arr[j]) {
                   count++;
               }
           }

       }
       /* Count is equal to length of the array
       * means no duplicates in the array
       */
       if(count==arr.length)
       return true;
       else
return false;
      
   }
}

________________

output:

Elements in Array1 are unique
Elements in Array2 are not unique

________________Thank YOu

 Write a method called is Unique that accepts an array of integers as a parameter and returns a boolean value indicating whether or not the values in the array
 Write a method called is Unique that accepts an array of integers as a parameter and returns a boolean value indicating whether or not the values in the array

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site