Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find duplicates between arrays

Tags:

c#

algorithm

Assume you are given two arrays of integers of constant length which is 3, and you are always sure that two elements of the given two arrray will have same values.

so assume array A has three values: a, b, c. and array B has three values: d, e, f.

we are sure that two of the values will be same. we are asked to put these four different values in an array of size 4, such that output array C, should have in indices 1 and 2 the same values from arrays A and B. and at indices 0 and 3 it should have the different values of array A and B. i have implemented it, but really not satisfied with this solution... does anyone has better solution idea? except the one that would put my counters in array... :)

int[] a = { 1, 201, 354 };
int[] b = { 404, 201, 354 };

int[] c = new int[4];

for (int i = 0; i < c.Length; i++)
{
    Console.WriteLine(c[i]);
}
like image 286
kl. Avatar asked Feb 11 '10 21:02

kl.


2 Answers

I'm sorry, I re-read more closely and I think this is what you want. Please advise. :)

int[] same = a.Intersect(b).ToArray(); ;
int[] diff = a.Union(b).Except(same).ToArray();
int[] c = new int[] { diff[0], same[0], same[1], diff[1] };
like image 120
Sapph Avatar answered Sep 22 '22 08:09

Sapph


What you are looking for is just a set of the two arrays (set contains every element once at most). The solution in c++:

#include <set>

int main () {
    int a[] = { 1,2,3 };
    int b[] = { 4,2,3 };

    std::set<int> s(a, a+3);
    s.insert(b, b+3);
}
like image 39
rmn Avatar answered Sep 22 '22 08:09

rmn