Last active
June 16, 2016 08:02
-
-
Save kumo/472043819fec7a3737f8 to your computer and use it in GitHub Desktop.
Roman Nums in Swift
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
//: Playground - noun: a place where people can play | |
import UIKit | |
extension Int { | |
func toRoman() -> String? { | |
var number = self | |
guard number > 0 else { | |
return nil | |
} | |
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 result = "" | |
for (romanChar, arabicValue) in values { | |
let count = number / arabicValue | |
if count == 0 { continue } | |
for _ in 1...count | |
{ | |
result += romanChar | |
number -= arabicValue | |
} | |
} | |
return result | |
} | |
} | |
13.toRoman() | |
(12+15).toRoman() | |
2015.toRoman() | |
0.toRoman() | |
extension String { | |
func toArabic() -> Int? { | |
var string = self as String | |
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 result = 0 | |
for (romanChars, arabicValue) in values { | |
let range = romanChars.startIndex ..< romanChars.endIndex | |
while string.hasPrefix(romanChars) { | |
result = result + arabicValue | |
#if swift(>=3.0) | |
string.removeSubrange(range) | |
#else | |
string.removeRange(range) | |
#endif | |
} | |
} | |
if (string.isEmpty) { | |
return result | |
} | |
return nil | |
} | |
} | |
"MCMXXV".toArabic() | |
"XIII".toArabic() | |
"R0B".toArabic() |
@kumo like this?
for (romanChars, arabicValue) in values {
while string.hasPrefix(romanChars) {
result = result + arabicValue
string = string.substringFromIndex(romanChars.endIndex)
}
}
Using ..<
for the range
Adding support for Swift 3 (removeSubrange instead of removeRange)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Pretty much the same as the previous Swift versions, but this time I preferred to use
removeRange
rather thansubstringFromIndex