Java Two-Dimensional Array Question

Hello everyone,

I need to be able to search a two dimensional java array for duplicate values, and then report which location has the duplicate value. How would I go about doing this?

I thought if I would subtract 1 from my col and row, that it would work in a double for loop, but I get an exception thrown because you cant have a -1 in an array...

How would I search my array for a duplicate value?

Here is my code:

 
boolean dupval = false;
		
		for(int row = 0; row < 3; row++)
		{
			int count = row;

			for(int col = 0; col < 3; col++)
			{
				
				String newVal = myArray[col][row].getText();
				int val = Integer.parseInt(newVal);
		
				previousVal = myArray[col-1][row-1].getText();
				prevInt = Integer.parseInt(previousVal);
		
				if(val == prevInt)
				{
					//report a duplicate error
					dupval = true;
				}
				count++;
			}
		}
		
		return dupval;

Open in new window


Thanks in advance,

Kody-Burg
LVL 6
Kody-BurgAsked:
Who is Participating?
 
cmalakarCommented:
And you can use Set to identify duplicate at any location.


boolean dupval = false;
Set<String> mySet = new HashSet<String>();		
		for(int row = 0; row < 3; row++)
		{
			for(int col = 0; col < 3; col++)
			{
				
				String newVal = myArray[col][row].getText();
				if(!mySet.add(newVal)){
                                 count++;  //Here is the duplicate     
                                 dupVal = true;                        
                                }
				
			}
		}
		
		return dupval;

Open in new window

0
 
objectsCommented:
for that approach you would start your indexes at 1


            for(int row = 1; row < 3; row++)
            {
                  int count = row;

                  for(int col = 1; col < 3; col++)
0
 
objectsCommented:
though with that your only checking each cell for a duplicate in the cell up and to the left. Is that what you intend?
0
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

 
for_yanCommented:
0
 
Kody-BurgAuthor Commented:
for_yan:

I don't want to remove the duplicate, I want to tell the user where the duplicate is.
0
 
for_yanCommented:
You want to start creating HashMap, where the key would be your values
and the value would be coordinates in the arrray, say "1-2","2-4",
As you'll be going thrugh array collecting your HashMap - you'll be
cchecking if such key exists and you'll be creating ArrayList of the vlues - of the coordinates
which have duplicates
0
 
objectsCommented:
to check all values you need more nested loops

for(int col = 0; col < 3; col++) {
    for(int row = 0; row < 3; row++) {
        // check for duplicates of value @ (col, row)
        check(myArray, col, row);
    }
}


where check() loops thought the array again checking the values



void check(int[][] array, int col, int row) {
   int val = array[row][col];
   for (int j=0; j<array.length; j++) {
      for (int i=0; i<array[j].length; i++) {
         if (val==array[j][i]) {
             // duplicate (col,row) and (j, i)
         }
      }
   }
}

Open in new window

0
 
Kody-BurgAuthor Commented:
cmalakar,

That is exactly what I needed. Thank you!
0
 
cmalakarCommented:
Did you check my comment ?

Where dupVal is being set to true, you can get the col and row index of duplicate element.
0
 
for_yanCommented:

Looks like it works, but I'll check with bigger arrays
import java.util.*;

public class ArrayDup {

    public static ArrayList getDup(String [][] arr, int N, int M){
        HashMap m0 = new HashMap();
        HashMap res = new HashMap();
        ArrayList al = new ArrayList();
        for(int j= 0; j<N; j++){
        for(int i=0; i<M; i++){
            if(m0.get(arr[j][i]) != null){
                String val = (String)m0.get(arr[j][i]);
                   boolean notAdded = true;
                for(int kk=0; kk<al.size(); kk++){
                    TreeSet s = (TreeSet) al.get(kk);

                    if(s.contains(j+"-"+i) && (!s.contains(val))){s.add(val);  notAdded = false;}
                    else
                     if(!s.contains(j+"-"+i) && (s.contains(val))){s.add(j+"-"+i); notAdded = false;}



                }
                if(notAdded){
                    TreeSet s1 = new TreeSet();
                    s1.add(val);
                    s1.add(j + "-" + i);
                    al.add(s1);

                }


            }
            else
            {
                m0.put(arr[j][i],j+"-"+i);
            }

        }
        }


        return al;

    }



public static void main(String [] args){
    String [][] ss = new String [2][2];
    ss[0][0] = "A";
    ss[0][1]="A";
    ss[1][0]="B";
    ss[1][1]="B";

    ArrayList al = getDup(ss,2,2);

    for(int j=0; j<al.size(); j++){
        TreeSet ts = (TreeSet)al.get(j);

        Iterator it = ts.iterator();
      while(it.hasNext())   {
            System.out.print((String)it.next()+ " ");
        }
    System.out.println("");
}

    }
}

Open in new window


Output:
0-0 0-1 
1-0 1-1 

Open in new window

0
 
for_yanCommented:

Also checked for [3x3] array:

import java.util.*;

public class ArrayDup {
    public static void main(String [] args){
    String [][] ss = new String [3][3];
    ss[0][0] = "A";

    ss[0][1]="B";
    ss[0][2]="D";


    ss[1][0]="C";
    ss[1][1]="A";
    ss[1][2]="C";
    ss[2][0]="C";
    ss[2][1]="F";
    ss[2][2]="B";
    ArrayList al = getDup(ss,3,3);

    for(int j=0; j<al.size(); j++){
        TreeSet ts = (TreeSet)al.get(j);

        Iterator it = ts.iterator();
      while(it.hasNext())   {
            System.out.print((String)it.next()+ " ");
        }
    System.out.println("");
         System.out.println("");
}

    }


    public static ArrayList getDup(String [][] arr, int N, int M){
        HashMap m0 = new HashMap();
        HashMap res = new HashMap();
        ArrayList al = new ArrayList();
        for(int j= 0; j<N; j++){
        for(int i=0; i<M; i++){
            if(m0.get(arr[j][i]) != null){
                String val = (String)m0.get(arr[j][i]);
                   boolean notAdded = true;
                for(int kk=0; kk<al.size(); kk++){
                    TreeSet s = (TreeSet) al.get(kk);

                    if(s.contains(j+"-"+i) && (!s.contains(val))){s.add(val);  notAdded = false;}
                    else
                     if(!s.contains(j+"-"+i) && (s.contains(val))){s.add(j+"-"+i); notAdded = false;}



                }
                if(notAdded){
                    TreeSet s1 = new TreeSet();
                    s1.add(val);
                    s1.add(j + "-" + i);
                    al.add(s1);

                }


            }
            else
            {
                m0.put(arr[j][i],j+"-"+i);
            }

        }
        }


        return al;

    }




}

Open in new window


Output:

0-0 1-1 

1-0 1-2 2-0 

0-1 2-2 

Open in new window

0
 
Kody-BurgAuthor Commented:
for_yan,

Thanks for the extra comments! Your extra code will no doubt help me in the future.
0
 
for_yanCommented:
I'm glad you appreciate.
As I'm sure you understand, this is of course the real solution to your question.
0
 
cmalakarCommented:
>>As I'm sure you understand, this is of course the real solution to your question

You don't need such complex hash map's to just find the index of the duplicate elements. A simple set will do the job, and lists the indexes.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.