Aabhi
Aabhi

Reputation: 11

Searching for repeated entries in a 2d integer array

I have a 2d integer array which has 3 numbers in each index.

For example:

   examplearray=new int[][]
   {

        {0, 0, 0},
        {0, 1, 0},
        {0, 0, 1},
        {1, 0, 1},

   };

I want to find out whether the first two numbers in each index match with the first 2 numbers at any other index.

In this example, {0,0,0} and {0,0,1} both have the same first two numbers. I'd like to create a code which can indicate this.

Upvotes: 1

Views: 67

Answers (2)

clancer
clancer

Reputation: 613

You could try this if you meant entries with the same first two digits as another entry

ArrayList<String> entries = new ArrayList<String>
for (int i = 0; i < examplearray.length; i++) {
  if (entries.indexOf( examplearray[i][0] + " " + examplearray[i][1] )) {
    // here is a duplicate
  } else {
    entries.add( examplearray[i][0] + " " + examplearray[i][1] );
  }
}

Upvotes: 0

sjr
sjr

Reputation: 9895

The best way is to create a key class that represents the members of the outer array. The hackiest/fastest way is to use a long to stuff the first two numbers together:

Set<Long> keys = new HashSet<>();
for (int[] innerArray : examplearray) {
  long key = ((long) innerArray[0] << 32) | innerArray[1];
  if (keys.contains(key)) {
    System.out.println(Arrays.toString(innerArray) + " has duplicate entries");
  }
  keys.add(key);
}

Upvotes: 2

Related Questions