Below is a function that prints out the intersection of two sets. I'd like to rewrite it using linked lists and recursively, but I just don't know where to start.. Could anyone walkthrough with me?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int intersection(int arr1[], int arr2[], int a, int b)
{
int i = 0, j = 0;
while (i < a && j < b)
{
if (arr1[i] < arr2[j])
i++;
elseif (arr2[j] < arr1[i])
j++;
else
{
printf(" %d ", arr2[j++]);
i++;
}
}
}
//intersection with an empty list gives you an empty list.
intersection([], _, []).
//if the first element is on the other list, then it is part of the intersection.
//you take the rest of the list and recurse
intersection([X|C], L, [X|Result]) :- member(X, L), intersection(C, L, Result).
//else, you simply discard the first element and recurse
intersection([_|C], L, Result) :- intersection(C,L,Result).
If you mantain the lists sorted then the member function may be optimized so you don't search from the start of the list.