I'm working through a kata about decoding Roman numerals into base 10 numbers and I'm running into a very strange problem. The problem I'm running into is that the output is not consistent and I have no idea why. I have the following code set up trying to beat the challenge (I know it's not perfect; that's not the problem):
package kata
import "strings"
var numeralsMap = map[string]int{
"M": 1000,
"D": 500,
"C": 100,
"L": 50,
"X": 10,
"V": 5,
"I": 1,
}
func Decode(roman string) int {
sum := 0
romanCpy := roman
for k := range numeralsMap { //works through romanCpy looking for matching numeralMap members
for strings.Index(romanCpy, k) != -1 {
index := strings.Index(romanCpy, k)
if index == 0 { //if it is the first one in the string, simply add it to sum and remove it from romanCpy
sum += numeralsMap[k]
if len(romanCpy) > 1 { //this is necessary to prevent an infinite loop at the last numeral
romanCpy = romanCpy[1:]
} else if len(romanCpy) <= 1 {
romanCpy = "" //removes last one at the end
}
} else if index > 0 { //if it is present but not the first one, subtract all the ones before it from sum
substr := romanCpy[:index]
for i := 0; i < len(substr); i++ {
sum -= numeralsMap[string(substr[i])]
}
if len(romanCpy) > 1 {
romanCpy = romanCpy[index:]
}
}
}
}
return sum
}
And then I have some tests like this:
t.Run("MDCLXVI", func(t *testing.T) {
got := Decode("MDCLXVI")
want := 1666
if got != want {
t.Errorf("got %d; want %d", got, want)
}
})
t.Run("IV", func(t *testing.T) {
got := Decode("IV")
want := 4
if got != want {
t.Errorf("got %d; want %d", got, want)
}
})
Then when I run the tests, sometimes they pass, and then sometimes the same test will fail the next time. This is true both on my machine and when I try to run the tests on codewars. I'm not asking for help to solve the kata, I'm just not sure why the output keeps changing. Any help would be greatly appreciated. Thanks in advance!
EDIT: The different outputs do tend to follow a pattern. It seems to loop around every five times.