Reputation: 1
I have an array (temp3
) of names.
I need determine if any name is equal to another name in the array, without repeating comparisons.
This is what I have so far, thanks.
for(int m=0; m<3; m++){
for(int n=0; n<3; n++){
if(m!=n){
if(temp3[m]==temp3[n]){
System.out.println("Yes");
}
}
}
}
Upvotes: 0
Views: 1781
Reputation: 33029
You could also do this without any explicit looping by using a Set
:
if (temp3.length != new HashSet<String>(Arrays.asList(temp3)).size()) {
System.out.println("Yes");
}
This works by checking if the final Set
has the same number of entries as the array. If not, then there must have been a duplicate. (This is actually an instance of the Pigeonhole Principle. I find it kind of funny that such a simple deduction needs a special name!)
Upvotes: 0
Reputation: 67019
This is a faster solution. We do not repeat any comparisons, and we automatically avoid comparing a string to itself.
for (int i=0; i< strings.length;i++) {
for (int j= i + 1; j<strings.length;j++) {
if (strings[i].equals(strings[j]))
System.out.println("The two strings are the same");
}
}
Upvotes: 1
Reputation: 7769
for(int i=0; i< strings.length;i++){ // Pick a string
for(int j=i+1; j<strings.length;j++){ // Loop on all strings starting from i+1
if(strings[i].equals(strings[j])) // check if the two strings are equal
System.out.println("The two strings are the same"); // SOP
}
}
}
Upvotes: 1