Skip to content

Instantly share code, notes, and snippets.

@glukianets
Created September 19, 2019 20:39
Show Gist options
  • Save glukianets/f51ba60f78248145683116f852afc545 to your computer and use it in GitHub Desktop.
Save glukianets/f51ba60f78248145683116f852afc545 to your computer and use it in GitHub Desktop.
Roman numeral parser: a swift one-liner
let numerals: [Character:Int] = ["I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000]
func parse(romanNumeral numeral: String) -> Int {
return numeral.compactMap { numerals[$0] }.reversed().reduce((0, 0)) { $0.1 <= $1 ? ($0.0 + $1, $1) : ($0.0 - $1, 0) }.0
}
assert(parse(romanNumeral: "MMXIX") == 2019)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment