Created
February 23, 2021 09:39
-
-
Save vitorventurin/252f6ab5d5199d4d4be54565cd3a2737 to your computer and use it in GitHub Desktop.
Legionaries: In the range 1-13 (1,2,3,4,5,6,7,8,9,10,11,12,13) the digit 1 occurs 6 times. In the range, 1 - 2,660 (half the number of Romans in a legion), expressed in Roman numerals, how many times does the numeral “X” occur?
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 | |
func toRoman(number: Int) -> String { | |
let romanValues = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"] | |
let arabicValues = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] | |
var romanValue = "" | |
var startingValue = number | |
for (index, romanChar) in romanValues.enumerated() { | |
let arabicValue = arabicValues[index] | |
let div = startingValue / arabicValue | |
if (div > 0) { | |
for _ in 0..<div { | |
romanValue += romanChar | |
} | |
startingValue -= arabicValue * div | |
} | |
} | |
return romanValue | |
} | |
func getCountOfCharacter(c: Character, stringArray: [String]) -> Int { | |
let joined = stringArray.joined() | |
return joined.filter { $0 == c }.count | |
} | |
/* | |
Legionaries: | |
In the range 1-13 (1,2,3,4,5,6,7,8,9,10,11,12,13) the digit 1 occurs 6 times. | |
In the range, 1 - 2,660 (half the number of Romans in a legion), expressed in Roman numerals, how many times does the numeral “X” occur? | |
*/ | |
var romanArray = [String]() | |
for i in 1...2660 { | |
romanArray.append(toRoman(number: i)) | |
} | |
let result = getCountOfCharacter(c: "X", stringArray: romanArray) | |
print(result) | |
// answer: 3977 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment