Inspired by the Romans

Roman inspirations
Rome

Inspired by the Romans

After two and a half weeks in Italy visiting the sites in Rome as well as Pompeii and Herculaneum, I have been reminded how impressive the Romans were. I still can’t really understand how the whole thing collapsed given how advanced they were.

With Trump in anti Muslim mode, perhaps we need to make contingency plans for getting rid of our politically incorrect Arabic numerals. Despite the impracticality of Roman numerals, the recent Brexit vote tells us that politics can easily override rational thinking. So in preparation (and perhaps in the spirit of the summer silly season), here’s a bit of Swift code for doing the necessary translations:

let charValues = ["I": 1,"V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000]

let numerals = [(1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (50, "L"),
                (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I")]

func fromRoman(roman: String) -> Int? {
    var result = 0
    var maxSoFar = 0
    for char in roman.characters.reversed() {
        guard let value = charValues[String(char)] else { return nil }
        if value >= maxSoFar {
            result += value
            maxSoFar = value
        } else {
            result -= value
        }
    }
    return result
}

func toRoman(int: Int, numerals: [(Int, String)] = numerals, cumulative: String = "") -> String {
    guard let (intValue, stringValue) = numerals.first else { return cumulative }
    let newNumerals = Array(numerals.dropFirst())
    if int >= intValue {
        let quotient = int / intValue
        let remainder = int % intValue
        let stringToAdd = String(repeating: stringValue, count: quotient)
        return toRoman(int: remainder, numerals: newNumerals, cumulative: cumulative + stringToAdd)
    } else {
        return toRoman(int: int, numerals: newNumerals, cumulative: cumulative)
    }
}

Meanwhile, I hope everyone is enjoying the MMXVI Olympics. Currently, the UK is number II in the medal table, which is amazing!