Skip to content

Instantly share code, notes, and snippets.

@kumo
Last active July 17, 2020 10:22
Show Gist options
  • Save kumo/44178f2246364ffef9bb to your computer and use it in GitHub Desktop.
Save kumo/44178f2246364ffef9bb to your computer and use it in GitHub Desktop.
Converting to Arabic numbers using tuples
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
@kumo
Copy link
Author

kumo commented Nov 27, 2019

Thanks for the feedback and corrections.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment