Created
October 30, 2024 00:22
-
-
Save DandyLyons/8ab7e104c25a9ed3d3a58967de1fb037 to your computer and use it in GitHub Desktop.
Unordered Equality Checking in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| extension Sequence where Element: Hashable { | |
| /// Count the number of occurrences of each value in a sequence | |
| public func countFrequency() -> [Element: Int] { | |
| var result = [Element: Int]() | |
| for element in self { | |
| result[element, default: 0] += 1 | |
| } | |
| return result | |
| } | |
| /// Check for sequence equality while ignoring order | |
| public func hasSameElements(as s2: Self) -> Bool { | |
| let freq1 = self.countFrequency() | |
| let freq2 = s2.countFrequency() | |
| return freq1 == freq2 | |
| } | |
| } | |
| extension Collection where Element: Hashable { | |
| /// Check for collection equality while ignoring order | |
| public func hasSameElements(as c2: Self) -> Bool { | |
| guard self.count == c2.count else { return false } | |
| let freq1 = self.countFrequency() | |
| let freq2 = c2.countFrequency() | |
| return freq1 == freq2 | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment