Jacky
Jacky

Reputation: 27

Finding if every number in 2D array is unique?

I'm trying to figure out how I can create a method that makes sure if every number in my 2d array is unique and not the same as any other number. This should be somewhat simple as my numbers can only be 1-9, and there'd only be 9 of them, but I still don't understand how I can find that out in a simple way without doing something like

if (array[0][0] == array[0][1] || array[0][0] == array[0][2])

and so forth all the way up to array[0][0] == array[2][2] for every single number. I'd have an extremely long group of nested if statements for 9 numbers, and I doubt my professor intended for us to do it this way.

So how can I use a loop to do what I want to do here? I've searched through other java 2d array unique algorithms on StackOverflow, but I couldn't find one that wanted to test every number against every other number with the rules I have set for my assignment. Keep in mind, I need to test each number against EVERY other number.

Here's my code so far:

class MagicSquare
{
   //2d array data member
   private int[][] array = {{}};

   /**
   Constructor: Initializes 2d array.
   @param arr The array.
   */
   public MagicSquare(int[][] arr)
   {
      array = arr;
   }

   /**
   This method displays all values from the elements
   in the array.
   */
   public void showArray()
   {
      for (int row = 0; row < 3; row++)
      {
         for (int col = 0; col < 3; col++)
         {
            System.out.println(array[row][col]);
         }
      }
   }

   /**
   showResult for later
   */
   public void showResult()
   {

   }

   /**
   This method determines if every number in the array
   is in the range of 1-9.
   @return The value of range.
   */
   private boolean isInRange()
   {
      boolean range = false;

      for (int row = 0; row < 3; row++)
      {
         for (int col = 0; col < 3; col++)
         {
            if (array[row][col] == 1 || array[row][col] == 2 || array[row][col] == 3 ||
                array[row][col] == 4 || array[row][col] == 5 || array[row][col] == 6 ||
                array[row][col] == 7 || array[row][col] == 8 || array[row][col] == 9)
            {
               range = true;
            }
            else
            {
               range = false;
               break;
            }
         }
      }

      return range;
   }

   /**

   */
   private boolean isUnique()
   {
      boolean unique = false;


   }



}

Upvotes: 1

Views: 2842

Answers (4)

Saurav Sahu
Saurav Sahu

Reputation: 13934

Since,

my numbers can only be 1-9

Replace this bulky code:

if (array[row][col] == 1 || array[row][col] == 2 || array[row][col] == 3 ||
                array[row][col] == 4 || array[row][col] == 5 || array[row][col] == 6 ||
                array[row][col] == 7 || array[row][col] == 8 || array[row][col] == 9)

with

if (array[row][col] >= 1 && array[row][col] <= 9)

Then

Use HashSet as suggested in comments, check the size of array i.e. col*row equals the size of set. In case of duplicate entry, the size of set is definitely going to be lesser.

Upvotes: 0

Nicholas K
Nicholas K

Reputation: 15423

You can do so very easily using java-8

int a[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int distinctValues = Arrays.stream(a).flatMapToInt(IntStream::of).distinct().count();

For the above example if each element in your array is distinct the value should be 9. If it's not distinct then the value will be less than 9.

This will work with any n-D array.

Upvotes: 1

Pushpesh Kumar Rajwanshi
Pushpesh Kumar Rajwanshi

Reputation: 18357

Put all the numbers in a Set and just match the size of array and set. If both are equal then all your numbers in array are unique. Let me know if you need code demo.

Edit 1:

Try this code,

public static void main(String[] args) throws Exception {

    Integer[] numbers = new Integer[] { 2, 3, 1, 7, 4, 6, 5, 11 };

    Set<Integer> numberSet = new HashSet<Integer>(Arrays.asList(numbers));

    if (numbers.length == numberSet.size()) {
        System.out.println("Numbers in array are unique");
    } else {
        System.out.println("Numbers in array are not unique");
    }

// for 2d array

    Set<Integer> number2dSet = new HashSet<Integer>();

    Integer[][] numbers2d = new Integer[][] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
    int numbers2dSize = 0;

    for (Integer[] num2d : numbers2d) {
        List<Integer> numberList = Arrays.asList(num2d);
        number2dSet.addAll(numberList);
        numbers2dSize += numberList.size();
    }

    if (numbers2dSize == number2dSet.size()) {
        System.out.println("Numbers in 2d array are unique");
    } else {
        System.out.println("Numbers in 2d array are not unique");
    }

}

Upvotes: 1

SomeDude
SomeDude

Reputation: 14228

If your elements are guaranteed to be only in the range 1 to arr.length*arr[0].length then you could do it like ( generalized for any array length ):

private boolean isEveryElementUnique( int[][] arr ) {

  boolean[] isOccupied = new boolean[arr.length*arr[0].length+1];
  for ( int i = 0; i < arr.length; i++ ) {
     for ( int j = 0; j < arr[0].length; j++ ) {
       if ( isOccupied[arr[i][j]] ) return false;
       isOccupied[arr[i][j]] = true;
     }
  }
  return true;
}

You don't need to build a Hashset for this. It has unnecessary overhead. For this case a simple boolean array would suffice.

Upvotes: 0

Related Questions