Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Java Two-Dimensional Array Question

Posted on 2011-05-11
14
Medium Priority
?
521 Views
Last Modified: 2012-05-11
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
0
Comment
Question by:Kody-Burg
  • 5
  • 3
  • 3
  • +1
14 Comments
 
LVL 92

Expert Comment

by:objects
ID: 35743351
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
 
LVL 92

Expert Comment

by:objects
ID: 35743355
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
 
LVL 23

Accepted Solution

by:
cmalakar earned 2000 total points
ID: 35743356
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 47

Expert Comment

by:for_yan
ID: 35743362
0
 
LVL 6

Author Comment

by:Kody-Burg
ID: 35743380
for_yan:

I don't want to remove the duplicate, I want to tell the user where the duplicate is.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35743394
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
 
LVL 92

Expert Comment

by:objects
ID: 35743404
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
 
LVL 6

Author Closing Comment

by:Kody-Burg
ID: 35743411
cmalakar,

That is exactly what I needed. Thank you!
0
 
LVL 23

Expert Comment

by:cmalakar
ID: 35743419
Did you check my comment ?

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

Expert Comment

by:for_yan
ID: 35743517

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
 
LVL 47

Expert Comment

by:for_yan
ID: 35743547

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
 
LVL 6

Author Comment

by:Kody-Burg
ID: 35743573
for_yan,

Thanks for the extra comments! Your extra code will no doubt help me in the future.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35743609
I'm glad you appreciate.
As I'm sure you understand, this is of course the real solution to your question.
0
 
LVL 23

Expert Comment

by:cmalakar
ID: 35743618
>>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

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this post we will learn different types of Android Layout and some basics of an Android App.
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Progress
Suggested Courses

579 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question