Skip to content

Instantly share code, notes, and snippets.

@koher
Last active September 25, 2017 01:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save koher/b94ec9ef7560a7dc7152ae1de2b82748 to your computer and use it in GitHub Desktop.
Save koher/b94ec9ef7560a7dc7152ae1de2b82748 to your computer and use it in GitHub Desktop.
let array = [2, 3, 3, 4, 7, 2, 1, 4, 0, 9, 1, 2]
// array の要素の値ごとに集計
// 2 が 3 個、 3 が 2 個 などを知りたい
let nToCount: [Int: Int] = array.reduce(into: [:]) { nToCount, n in
nToCount[n, default: 0] += 1
}
// 結果を表示
for (n, count) in (nToCount.sorted { $0.key < $1.key }) {
print("\(n): \(count)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment