I have some C code I want to modify really simple.
Let's say I have two arrays like this
int v1[5] = {1, 3, 7, 13, 10};
int v2[2] = {1, 10};
And I would like to print the not common elements (difference) like:
3, 7, 13
Here is my attempt which is not enough yet:
#include <stdio.h>
int main()
{
int v1[5] = { 1, 3, 7, 13, 10 };
int v2[2] = { 1, 10 };
for (int i = 0; i < sizeof(v1) / (sizeof * v1); i++) {
for (int j = 0; j < sizeof(v2) / (sizeof * v2); j++) {
if (v1[i] != v2[j]) {
printf("%d ", v1[i]);
break;
} else {
break;
}
}
}
return 0;
}
The two arrays will be always really short (max 6 elements). Thery are not ordered and I should not modify them. The elements in each of them are unique, that is each number can only appear 1 time in each array. v2 will only contains a subset of element from v1. What would be the most efficient way to achieve this?
You could start by taking any array and iterating it element by element and finding if that element is in second array too by a nested for loop and putting an if condition in the inner for loop and storing the common element in another array and then comparing both of the array one by one with that array and putting uncommon element in another array.
Like:
int a[min(l1,l2)], b[l], x = 0, k = 0, flag = 1;
for(int i=0; i<l1; i++){
for(int j=0; j<l2; j++){
if(v1[i]==v2[j]){
a[k] = v1[i];
k++;
}
}
}
for(int i=0; i<l1; i++){
flag = 1;
for(int j=0; j<k; j++){
if(v1[i] == a[j]){
flag = 0;
break;
}
}
if(flag==1){
b[x] = v1[i];
x++;
}
}
for(int i=0; i<l2; i++){
flag = 1;
for(int j=0; j<k; j++){
if(v2[i] == a[j]){
flag = 0;
break;
}
}
if(flag==1){
b[x] = v2[i];
x++;
}
}
Afterwards you can print the array.