Hello everyone! I’m starting an algorithms series where we take famous algorithms written in other languages (I’m focusing on C/C++) and translate them to Zig code.
Our target is Symmetric Difference - this algorithm populates an output set with the difference between the two input sets.
Note
:
Input sets are sorted.
Output set is sorted.
Example:
Input:
Set A: {1, 2, 3, 4, 5, 6, 7, 8};
Set B: {5, 7, 9, 10};
Output:
Set C: { 1, 2, 3, 4, 6, 8, 9, 10 }
Here is a possible implementation in C++ from: std::set_symmetric_difference - cppreference.com
template<class InputIt1, class InputIt2, class OutputIt, class Compare>
OutputIt set_symmetric_difference(InputIt1 first1, InputIt1 last1,
InputIt2 first2, InputIt2 last2,
OutputIt d_first, Compare comp)
{
while (first1 != last1)
{
if (first2 == last2)
return std::copy(first1, last1, d_first);
if (comp(*first1, *first2))
*d_first++ = *first1++;
else
{
if (comp(*first2, *first1))
*d_first++ = *first2;
else
++first1;
++first2;
}
}
return std::copy(first2, last2, d_first);
}
Bonus Challenge:
Since this algorithm only requires Forward Iterators
, write a version that uses a theoretical ForwardIterator (can be represented as anytype
) that has a next
function that advances the iterator by one place and a get
function that returns a pointer to the value being referenced.