The exercise is about performing the union of two character string arrays.
Ex:
A={"a","b","c"}
B={"a","e"}
AB={"a","b","c","e",null}
The size of the array for the union can be the sum of the size of the other arrays, so there can be values null
in the union.
The code that I have joins two Arrays but it does not return me null
if two values are repeated.
public class Union{
public static String[] union(String[] vec1, String[] vec2){
String[] vec3= new String[vec1.length+vec2.length];
int i=0;
for(i=0;i<vec1.length;i++){
vec3[i]=vec1[i];
}
for(int j=0;j<vec2.length;j++){
int n=0;
if (vec1[n]!=vec2[j]){
vec3[i]=vec2[j];
n++;
i++;
}
if(vec1[n] == vec2[j]){
vec3[i]=null;
n++;
i++;
}
}
return vec3;
}
}
One way to do them is using HashSet, you create a HashSet to add the values of Array A and B to perform the union, then you initialize an Array with the sum of the length of both arrays and finally insert the values
Departure:
I managed to do it without Hash! Obviously it would be best to use them.
2 for loops are created, one makes the first interaction and saves the value and the index entered so far, the second what it does is go through the entire array checking if there is any value that is equal to that saved value, but that the index is different (obviously), and it is also checked if it differs from
null
the inserted object since if it does not giveNullPointerException
In this way, pInteraction would be the first loop and sInteraction is the second loop, if it happens to be repeated, we change it to
null
.I used
System.arraycopy()
to copy array1 and array2 into the return array, but you can still copy manually with a for loop, that's just optional.Departure:
another way to do it
What I can think of is:
First
Convert the duplicate values of vector 2 to null and copy all the values of vector 1 to vector 3
Second
By having null elements in vector 2, we copy the non-null values in vector 3
Remark
When comparing strings you have to use the method
equals()
instead of the comparison==
I would do it in the following way and I could join more arrays just by modifying the arraycopy
output [a,b,c,e]