Skip to content

Instantly share code, notes, and snippets.

@mredig
Created June 5, 2019 15:52
Show Gist options
  • Save mredig/1369fd5491cb148a4b44042344242a27 to your computer and use it in GitHub Desktop.
Save mredig/1369fd5491cb148a4b44042344242a27 to your computer and use it in GitHub Desktop.
roman numerals - it's ugly but it works
import Foundation
extension Int {
subscript(digitIndex: Int) -> Int? {
print(self)
var decimalBase = 1
for _ in 0..<digitIndex {
decimalBase *= 10
}
return (self / decimalBase) % 10
}
func romanNumerals() -> String {
var index = 0
var out = ""
while let value = self[index] {
guard let tensPlace = TensPlace(rawValue: index) else {
break
}
out = "\(romanNumeral(for: value, tensPlace: tensPlace))\(out)"
index += 1
}
return out
}
private enum TensPlace: Int {
case ones = 0
case tens
case hundreds
case thousands
}
private func romanNumeral(for digit: Int, tensPlace: TensPlace) -> String {
var out = ""
switch tensPlace {
case .ones:
if digit < 4 {
out = (0..<digit).map { _ in "I" }.joined()
} else if digit == 4 {
out = "IV"
} else if digit < 9 {
out = "V"
out += (5..<digit).map { _ in "I" }.joined()
} else {
out = "IX"
}
case .tens:
if digit < 4 {
out = (0..<digit).map { _ in "X" }.joined()
} else if digit == 4 {
out = "XL"
} else if digit < 9 {
out = "L"
out += (5..<digit).map { _ in "X" }.joined()
} else {
out = "XC"
}
case .hundreds:
if digit < 4 {
out = (0..<digit).map { _ in "C" }.joined()
} else if digit == 4 {
out = "CD"
} else if digit < 9 {
out = "D"
out += (5..<digit).map { _ in "C" }.joined()
} else {
out = "CM"
}
case .thousands:
out = (0..<digit).map { _ in "M" }.joined()
}
return out
}
}
1.romanNumerals()
3.romanNumerals()
4.romanNumerals()
5.romanNumerals()
8.romanNumerals()
9.romanNumerals()
11.romanNumerals()
32.romanNumerals()
42.romanNumerals()
55.romanNumerals()
74.romanNumerals()
98.romanNumerals()
101.romanNumerals()
202.romanNumerals()
402.romanNumerals()
445.romanNumerals()
853.romanNumerals()
911.romanNumerals()
999.romanNumerals()
1002.romanNumerals()
3052.romanNumerals()
9004.romanNumerals()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment