Skip to content Skip to sidebar Skip to footer

Symmetric Difference Between Arrays

I have been writing the code to make a symmetric difference between to or more arrays. As you know, the symmetric difference is about excluding the elements which are in both sets

Solution 1:

When you do the splice, the indexing of the array is changed. So it would skip some values.

In your example, prev = [1,2,3] and next = [5,2,1,4].

After the first splice @ key = 1 both arrays look like this prev = [1,3] and next = [5,1,4]. The next key is 2 which skips the entry 1 in next. Because of the splice, this index has shifted one to the left.

My solutions (sorry, I'm on my phone else I'd have written code)

  1. Write a more deliberate loop, and increment key only when necessary. So if there's a splice, don't increment, because the would-be next entry has been shifted to the current key.
  2. If you must keep the for a in b-type loop, consider having a duplicate but constant reference for the next array

Post a Comment for "Symmetric Difference Between Arrays"