reduce a list of roman numerals to a list of sets of consecutive roman numerals in swift

You can use a loop to iterate through the list of roman numerals and detect consecutive ones. For this, you can convert the roman numerals to integers using a dictionary and then check if the current element is greater than or equal to the previous one. If they are consecutive, you can add them to a set, otherwise, create a new set. Here's an implementation:

main.swift
func reduceToConsecutiveSets(romanNumerals: [String]) -> [[String]] {
    let romanToInt: [String: Int] = ["I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000]
    var result: [[String]] = []
    var currentSet: [String] = []
    
    for (index, romanNumeral) in romanNumerals.enumerated() {
        let value = romanToInt[romanNumeral]!
        let previousValue = index > 0 ? romanToInt[romanNumerals[index - 1]]! : 0
        
        if value >= previousValue {
            currentSet.append(romanNumeral)
        } else {
            result.append(currentSet)
            currentSet = [romanNumeral]
        }
    }
    
    result.append(currentSet)
    return result
}
688 chars
21 lines

Here's an example usage:

main.swift
let numerals = ["I", "I", "V", "X", "X", "X", "I", "V", "I"]
let result = reduceToConsecutiveSets(romanNumerals: numerals)
print(result) // Output: [["I", "I"], ["V"], ["X", "X", "X"], ["I", "V"], ["I"]]
204 chars
4 lines

This will output [[I, I], [V], [X, X, X], [I, V], [I]], which is a list of sets of consecutive roman numerals.

gistlibby LogSnag