/* Include lib */
#include <stdio.h>
/* Define */
#define ARRAY_MAX1 6
#define ARRAY_MAX2 8
#define ARRAY_MAX3 10
int array1[ARRAY_MAX1] = { 0, 1, 2, 3, 4, 5 };
int array2[ARRAY_MAX2] = { 9, 10, 2, 6, 7, 15, 2, 1 };
int array3[ARRAY_MAX3] = { 1, 8, 19, 20, 33, 12, 2, 1, 9, 43 };
/* API */
/* API linear search, return location >= 0 as soon as found. Otherwise return <= 0 */
int linear_search(int *arr, int size, int key)
{
int i;
if (!arr || size == 0) {
printf("Wrong input !!\n");
return -2;
}
for (i = 0; i < size; i++) {
if (key == arr[i])
return i;
}
return -1;
}
/* API count a value appear how many times in array */
int array_count_appearance(int *arr, int size, int key)
{
int i, ret, pos, cnt = 0;
if (!arr || size == 0) {
printf("Wrong input !!\n");
return -2;
}
pos = 0;
do {
ret = linear_search(&arr[pos], size, key);
if (ret >= 0) {
cnt++;
pos = ret + 1;
size = size - pos;
if (size <= 0)
break;
}
} while (ret >= 0);
return cnt;
}
/* Main func interract with user */
int main()
{
#if 1 /* Method 1: array have limit elements */
int common_found[ARRAY_MAX3] = { 0 };
int common_size = 0;
int i, cnt = 0;
/* Loop each element in array1, linear search it in array 2, then array3. Count and jump next array if found */
cnt = 0;
for (i = 0; i < ARRAY_MAX1; i++) {
cnt = 1;
if (linear_search(&array2[0], ARRAY_MAX2, array1[i]) >= 0)
cnt++;
if (linear_search(&array3[0], ARRAY_MAX3, array1[i]) >= 0)
cnt++;
/* If it appears in 3 array, printout and store */
if (cnt == 3) {
printf("Found element value %d appears in %d arrays\n", array1[i], cnt);
common_found[common_size++] = array1[i];
}
}
/* With each store, find it repeated how many times in each array by linear search */
for (i = 0; i < common_size; i++) {
cnt = array_count_appearance(&array1[0], ARRAY_MAX1, common_found[i]);
if (cnt >= 0)
printf("Found element value %d appears %d times in ARRAY1\n", common_found[i], cnt);
cnt = array_count_appearance(&array2[0], ARRAY_MAX2, common_found[i]);
if (cnt >= 0)
printf("Found element value %d appears %d times in ARRAY2\n", common_found[i], cnt);
cnt = array_count_appearance(&array3[0], ARRAY_MAX3, common_found[i]);
if (cnt >= 0)
printf("Found element value %d appears %d times in ARRAY3\n", common_found[i], cnt);
}
#endif
#if 0 /* Method 2: array have too many elements */
/* Sort array or assume these array sorted before */
/* Loop each element in array1, binary search it in array 2, then array3. Count and jump next array if found */
/* If it appears in 3 array, printout and store */
/* With each store, find it repeated how many times in each array by linear search */
#endif
}
To embed this project on your website, copy the following code and paste it into your website's HTML: