Created
September 19, 2019 20:39
-
-
Save glukianets/f51ba60f78248145683116f852afc545 to your computer and use it in GitHub Desktop.
Roman numeral parser: a swift one-liner
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
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