Last active
January 27, 2022 19:06
-
-
Save jrBordet/262b6498631553043d6c9dd9eb7495df to your computer and use it in GitHub Desktop.
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
enum Roman: String { | |
case M, D, C, L, X, V, I | |
init(_ v: String) { | |
self.init(rawValue: v)! | |
} | |
} | |
extension Roman { | |
var int: Int { | |
switch self { | |
case .M: | |
return 1000 | |
case .D: | |
return 500 | |
case .C: | |
return 100 | |
case .L: | |
return 50 | |
case .X: | |
return 10 | |
case .V: | |
return 5 | |
case .I: | |
return 1 | |
} | |
} | |
} | |
extension Array where Element == Roman { | |
func toArab(_ i: Int = 0, acc: Int = 0) -> Int { | |
guard i < self.count - 1 else { | |
return acc + self[i].int | |
} | |
let current = self[i].int | |
let next = self[i + 1].int | |
return current < next | |
? toArab(i + 1, acc: acc - current) | |
: toArab(i + 1, acc: acc + current) | |
} | |
} | |
let toArabResult = "MCMXC".map { Roman(String($0)) }.toArab() | |
print(toArabResult) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment