Skip to content

Instantly share code, notes, and snippets.

@jayrhynas
Created December 21, 2021 15:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jayrhynas/aaef9a6099f78b787dde233e48adf831 to your computer and use it in GitHub Desktop.
Save jayrhynas/aaef9a6099f78b787dde233e48adf831 to your computer and use it in GitHub Desktop.
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