Last active
July 17, 2020 10:22
-
-
Save kumo/44178f2246364ffef9bb to your computer and use it in GitHub Desktop.
Converting to Arabic numbers using tuples
This file contains 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
import UIKit | |
func toArabic(romanNumerals: String) -> Int? { | |
let values = [("M", 1000), ("CM", 900), ("D", 500), ("CD", 400), ("C",100), ("XC", 90), ("L",50), ("XL",40), ("X",10), ("IX", 9), ("V",5),("IV",4), ("I",1)] | |
var romanNumerals = romanNumerals | |
var result = 0 | |
for (romanChars, arabicValue) in values { | |
let range = romanChars.startIndex ..< romanChars.endIndex | |
while romanNumerals.hasPrefix(romanChars) { | |
result = result + arabicValue | |
romanNumerals.removeSubrange(range) | |
} | |
} | |
guard (romanNumerals.isEmpty) else { | |
return nil | |
} | |
return result | |
} | |
toArabic(romanNumerals: "MCM") // Some 1,900 | |
toArabic(romanNumerals: "MCMZ") // nil | |
toArabic(romanNumerals: "ROB") // nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the feedback and corrections.