Last active
March 15, 2023 13:20
-
-
Save vikingosegundo/5ce61de1b5f649bb3fa4ab4ede936f51 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
import Foundation | |
extension Int { | |
func times(_ text: String) -> String { | |
(0..<self).reduce(""){ e, _ in e + text } | |
} | |
} | |
let digits = [ | |
("I", "V", "X"), | |
("X", "L", "C"), | |
("C", "D", "M") | |
] | |
let exchangeRules: ((l:String, m:String, h:String)) -> [(Int, String, String)] = { r in | |
[ | |
(10, r.l, r.h), | |
( 9, r.l, r.l+r.h), | |
( 5, r.l, r.m), | |
( 4, r.l, r.l+r.m) | |
] | |
} | |
func roman(for n:Int, digits: [(String, String, String)] = digits) -> String { | |
digits | |
.reduce(n.times(digits[0].0)) { | |
exchangeRules($1) | |
.reduce($0) { | |
$0.replacingOccurrences(of: $1.0.times($1.1), with: $1.2) | |
} | |
} | |
} | |
func from(roman: String, digits: [(String, String, String)] = digits) -> Int { | |
digits | |
.reversed() | |
.reduce (roman) { | |
exchangeRules($1) | |
.reversed() | |
.reduce($0) { | |
$0.replacingOccurrences(of: $1.2, with: $1.0.times($1.1)) | |
} | |
}.count | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment