Created
December 21, 2021 15:27
-
-
Save jayrhynas/aaef9a6099f78b787dde233e48adf831 to your computer and use it in GitHub Desktop.
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
func sortedCount(of input: [String]) -> [(String, Int)] { | |
input.reduce(into: [String: (index: Int, count: Int)]()) { state, str in | |
var info = state[str] ?? (index: state.count, count: 0) | |
info.count += 1 | |
state[str] = info | |
}.sorted { lhs, rhs in | |
lhs.value.index < rhs.value.index | |
}.map { | |
($0.key, $0.value.count) | |
} | |
} | |
print(sortedCount(of: ["Wake up", "Do physics", "Play with a pet", "Do physics"])) | |
// [("Wake up", 1), ("Do physics", 2), ("Play with a pet", 1)] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment