Skip to content

Instantly share code, notes, and snippets.

@DigitalLeaves
Last active March 6, 2017 18:16
Show Gist options
  • Save DigitalLeaves/70dd30c4d82f856942b7cffa218169f5 to your computer and use it in GitHub Desktop.
Save DigitalLeaves/70dd30c4d82f856942b7cffa218169f5 to your computer and use it in GitHub Desktop.
A convenient function to get all common elements from two given sequences.
func commonElementsInSequences <T, U> (_ a: T, _ b: U) -> [T.Iterator.Element] where T: Sequence, U: Sequence, T.Iterator.Element: Equatable, T.Iterator.Element == U.Iterator.Element {
var returnArray:[T.Iterator.Element] = []
for aItem in a {
for bItem in b {
if aItem == bItem {
returnArray.append(aItem)
}
}
}
return returnArray
}
var one = ["orange", "carrot", "banana"]
var other = ["orange", "banana", "apple"]
var result = commonElementsInSequences(one, other)
print(result) //prints ["orange", "banana"]
@AnselmeKotchap
Copy link

Hello, I was wondering why didn't use contains(:) for the second loop? Is the contains function less efficient?

I also find the functional approach sorter, what do you think of it?:

func commonElementsInSequencesVersion_2 <T, U> (_ a: T, _ b: U) -> [T.Iterator.Element] where T: Sequence, U: Sequence, T.Iterator.Element: Equatable, T.Iterator.Element == U.Iterator.Element {

    return a.filter{b.contains($0)}

}

@DigitalLeaves
Copy link
Author

DigitalLeaves commented Mar 6, 2017

Hi there Anselme! Sorry, I didn't see your comment before.
Well, it's semantically slightly different. In this case, I'm interested in getting all occurrences of all the elements in both arrays that happen to be in the other array too. The devil, in this case, is in the details. Using your approach (which I really like and it's definitely shorter and more readable), you end up getting the elements of a that are in b, but you won't get the elements of b that are contained in a too.

This is an example of a different result using both functions:
var one = ["orange", "carrot", "banana", "banana"]
var other = ["orange", "banana", "apple","orange", "banana"]

var result = commonElementsInSequences(one, other)
var result2 = commonElementsInSequencesVersion_2(one, other)
print(result)
print(result2)
// prints:
["orange", "orange", "banana", "banana", "banana", "banana"]
["orange", "banana", "banana"]

All in all, I use this a lot for my applications, but I suppose that for other use cases, your approach is better and gives you the results you are after. Thanks for your comment!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment