Skip to content

Instantly share code, notes, and snippets.

@zonble
Created January 31, 2018 18:07
Show Gist options
  • Save zonble/2d08395fd94c67acc0d6fc8b7003aadc to your computer and use it in GitHub Desktop.
Save zonble/2d08395fd94c67acc0d6fc8b7003aadc to your computer and use it in GitHub Desktop.
import Foundation
func solution(_ n: Int) -> Int {
func fac(_ n: Int) -> Int {
if n == 1 {
return 1
}
return (1...n).reduce(1, *)
}
let strN = "\(n)"
let digitCount = strN.count
if digitCount == 1 {
return 1
}
var charMap = [Character: Int]()
for i in strN {
charMap[i] = (charMap[i] ?? 0) + 1
}
var total = charMap.reduce(fac(digitCount)) { (l, r) in
return l / fac(r.value)
}
if let zeroCount = charMap["0"] {
let count = zeroCount - 1
var excludeCharMap = charMap
if count == 0 {
excludeCharMap.removeValue(forKey: "0")
} else {
excludeCharMap["0"] = count
}
let exclude = excludeCharMap.reduce(fac(digitCount - 1)) { (l, r) in
return l / fac(r.value)
}
total = total - exclude
}
return total
}
func test(_ n: Int) {
print("\(n) \(solution(n))")
}
test(0)
test(1)
test(2)
test(100)
test(123)
test(1132)
test(99998)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment