Reputation: 1
I have a task: find mismatched elements of two arrays and move them to a third array. I understand how to find matched elements but how do I find mismatched elements? Here is my code for match elements:
String[] = first_arr = {"Den", "Michel", "Dana", "Sophie" "Clar" };
String[] = sec_arr = {"Michel", "Sophie", "Clar" };
String[] = res_arr = new String[first_arr.-length];
Int count = 0;
For(int i=0; i<first_arr.length; i++) {
for(int j=0; i<sec_arr.length; i++){
if(first_arr[i].equals(sec_arr[i])) {
res_arr[count++] = first_arr[i];
}
}
}
Upvotes: 0
Views: 815
Reputation: 409
Without using any class or external method this would be a working solution:
String[] first_arr = {"Den", "Michel", "Dana", "Sophie", "Clar"};
String[] sec_arr = {"Michel", "Sophie", "Clar"};
String[] temp_arr = new String[first_arr.length + sec_arr.length];
int count = 0;
for (int i = 0; i < first_arr.length; i++) {
boolean contains = false;
for (int j = 0; j < sec_arr.length; j++) {
if (first_arr[i].equals(sec_arr[j])) {
contains = true;
break;
}
}
if (!contains) {
temp_arr[count++] = first_arr[i];
}
}
for (int i = 0; i < sec_arr.length; i++) {
boolean contains = false;
for (int j = 0; j < first_arr.length; j++) {
if (sec_arr[i].equals(first_arr[j])) {
contains = true;
break;
}
}
if (!contains) {
temp_arr[count++] = sec_arr[i];
}
}
String[] res_arr = new String[count];
for (int i = 0; i < count; i++) {
res_arr[i] = temp_arr[i];
}
but the collection methods mentioned by shashank would propably be the way to go.
EDIT just did some quick tests and (always same names, 5 and 4 names) and it says that using no classes and other methods is about 20 times faster on average (100 iterations). not very reliable test but i was curious how much difference there is.
Upvotes: 1
Reputation: 347
I am assuming you want to find the unique elements in 2 different arrays. You can use collection methods to find the unique elements
List<String> list1 = Arrays.asList("a","b","c","d");
List<String> list2 = Arrays.asList("a","c");
Set<String> both = new HashSet<String>(list1);
both.addAll(list2);
Set<String> common = new HashSet<String>(list1);
common.retainAll(list2);
both.removeAll(common);
for (String s : both) {
System.out.println(s);
}
Upvotes: 0