Created
May 7, 2020 00:45
-
-
Save jakehawken/d47d80e5f53a14021303f3a9724bded6 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
extension String { | |
func occurrencesOfCharacter(_ character: Character) -> Int { | |
var count = 0 | |
for char in self { | |
if char == character { | |
count += 1 | |
} | |
} | |
return count | |
} | |
} | |
class RomanNumeralAnalyzer { | |
private static let decimals = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] | |
private static let numerals = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"] | |
static func romanNumeralForInt(_ number: Int) -> String { | |
var output = "" | |
var number = number | |
while number > 0 { | |
for (index, decimal) in decimals.enumerated() { | |
if number - decimal >= 0 { | |
number -= decimal | |
output += numerals[index] | |
break | |
} | |
} | |
} | |
return output | |
} | |
static func numberOfXsBetween1And(_ number: Int) -> Int { | |
guard number > 0 else { | |
return 0 | |
} | |
let xChar = Character("X") | |
let numerals = (1...number).compactMap { romanNumeralForInt($0) } | |
return numerals.map { (numeral) -> Int in numeral.occurrencesOfCharacter(xChar) } | |
.reduce(into: 0, +=) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment