I have this code in my Roman Numeral conversion algorithm...
for (a, r) in arabicToRomanArray where substring.hasPrefix(r) {
arabic += a
let index = substring.index(substring.startIndex, offsetBy: r.characters.count)
substring = substring.substring(from: index)
break
}
I was wondering if there is an easier way of doing this.
At the moment I am doing a conditional for loop and then breaking on the first entry. Is there a way to do a for first
type block with the condition?
The only way I can think of doing it is to filter the array and then get the first object from the filtered array and use that. Seems clunkier than what I'm doing at the moment though.
Edit
After trying out the edit it also makes the algorithm much slower, which makes sense.
The for/break loop will have a best time of O(1) and worst time of O(n).
The filter and first method will have a best time of O(n).