Created
March 22, 2015 10:02
-
-
Save avihut/799df542ca9228b753fe to your computer and use it in GitHub Desktop.
This file contains hidden or 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
func romanify(n: Int) -> String { | |
let pivotRomans = [ | |
1: "I", | |
4: "IV", | |
5: "V", | |
9: "IX", | |
10: "X", | |
40: "XL", | |
50: "L", | |
90: "XC", | |
100: "C", | |
400: "CD", | |
500: "D", | |
900: "CM", | |
1000: "M" | |
] | |
var roman = "" | |
var remaining = n | |
while remaining > 0 { | |
let pivotValues = Array(pivotRomans.keys).sorted(>) | |
var i = 0 | |
for ; remaining < pivotValues[i]; i++ {} | |
let highestPivot = pivotValues[i] | |
roman += pivotRomans[highestPivot]! | |
remaining -= highestPivot | |
} | |
return roman | |
} | |
assert(romanify(1) == "I", "Did not convert 1 to roman properly") | |
assert(romanify(2) == "II", "Did not convert 2 to roman properly") | |
assert(romanify(3) == "III", "Did not convert 3 to roman properly") | |
assert(romanify(4) == "IV", "Did not convert 4 to roman properly") | |
assert(romanify(5) == "V", "Did not convert 5 to roman properly") | |
assert(romanify(6) == "VI", "Did not convert 6 to roman properly") | |
assert(romanify(8) == "VIII", "") | |
assert(romanify(9) == "IX", "") | |
assert(romanify(10) == "X", "") | |
assert(romanify(14) == "XIV", "") | |
assert(romanify(15) == "XV", "") | |
assert(romanify(19) == "XIX", "") | |
assert(romanify(20) == "XX", "") | |
assert(romanify(40) == "XL", "") | |
assert(romanify(66) == "LXVI", "") | |
assert(romanify(99) == "XCIX", "") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also consider not using a map, since it makes you need to sort which isn't great