English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

i want to compare all elements of the first array to the second set of elements of the second array. the first set of arrays are randomed and the second set came from the user. i want to count how many elements they have in common... how will i do it?

2007-01-20 14:43:25 · 4 answers · asked by Sammy Baby 1 in Computers & Internet Programming & Design

im using c language

2007-01-20 16:37:49 · update #1

4 answers

Specify a language, please.

UPDATE:

Which / whose version of C, please?

2007-01-20 15:00:12 · answer #1 · answered by Anonymous · 0 0

The obvious answer is to do a nested loop. But that'll render a time of O(n^2), if it's a short array then it's fine. But if you want performance then you can use some sorted tree (assuming the elements you are comparing have some kind of order) to compare the elements. First construct a tree using the first array, then go through the second array to see if any elements are in the first one. Using this approach, the time will be about n*O(2*log(n)), which is better than before. Of course you can also sort both arrays and then go through them at the same to match the elements. That'll give you a time of 2n*O(log(n) ) + 2n. So I guess my answer is it depends on how efficient you want the implementation and how much work are you willing to do. Of course if you're using Java then I would just convert the arrays to lists and perform a list1.containsAll(list2).

2007-01-20 23:50:45 · answer #2 · answered by LostMonkey 2 · 0 0

you'll need to compare all elements in the first array to the elements in the second array, so the best option would be to use some type of nested look structure. Keep in mind that comparing large array sizes could use precious computer time so if your comparing a massive amount of elements plan for this in your algorithms.

2007-01-20 23:17:09 · answer #3 · answered by D 4 · 0 0

Use a nested loop. Assume that your two arrays, my_array_1 and my_array_2 are passed in to the function.

I'm not entirely sure what your desired end result is, so if the same item appears in an array more than once you'll get a result that may be undesirable.

int num_equal = 0;
int i, j;

for(i = 0; i < array_size; i++) {
for(j = 0; j < array_size; i++) {
if (my_array_1[i] == my_array_2[j]) {
num_equal = num_equal + 1;
}
}
}

2007-01-20 22:53:11 · answer #4 · answered by EC 3 · 0 0

fedest.com, questions and answers