Reputation: 97
I have a collection of lock combinations that is being outputed. I want to make sure that no combination is repeated. The combinations are not just ints. I converted them all to Strings for simplicity of the format. What is the line of code that allows me to loop and compare each string so that none are repeated? Any ideas? e.g 2D arrays
Thank you.
Upvotes: 2
Views: 184
Reputation: 9971
Encapsulate each combination as a List via Arrays.asList(T... a) to keep their ordering and store those in a HashSet to ensure uniqueness and constant time performance on contains(Object o) to determine if it's already present.
import java.util.Arrays;
import java.util.List;
import java.util.HashSet;
public class UniqueLocks {
public static void main (String[] args) {
List lock1 = Arrays.asList("1", "22", "333");
List lock2 = Arrays.asList("a", "bb", "ccc");
List lock3 = Arrays.asList("eee", "bbb", "ccc");
HashSet uniqueLocks = new HashSet(Arrays.asList(lock1, lock2, lock3));
List duplicateLock = Arrays.asList("1", "22", "333");
if (uniqueLocks.contains(duplicateLock)) {
System.out.println("Lock [" + duplicateLock + "] already present.");
}
}
}
Upvotes: 1
Reputation: 2095
Not sure what language your planning to do this with but you can check to see if two strings have the same value in C# like so
String myString = "Hello World!";
String myString2 = "Hello World!";
if(myString.equals(myString2)) {
//do something cause we have a match
}
if you have an array of strings you can just loop through them.
its very similar in other languages like java, vb.net.
EDIT: the java tag was added after I started writing my answer.. sorry
Hope this helps,
Upvotes: 0
Reputation: 4443
It might be easier to store your lock combinations in a set. This would make it much easier to ensure that they are unique.
This will be much faster too, since you do not need to compare every string with all of the other strings in your dataset...
Upvotes: 3