我正在研究将罗马数字解码为 10 进制数字的 kata,但我遇到了一个非常奇怪的问题。我遇到的问题是输出不一致,我不知道为什么。我设置了以下代码来尝试克服挑战(我知道它并不完美;这不是问题):
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
}
然后我有一些这样的测试:
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)
}
})
然后,当我运行测试时,有时它们会通过,有时相同的测试下次会失败。在我的机器上以及当我尝试在 codewars 上运行测试时都是如此。我不是在寻求帮助来解决 kata,我只是不确定为什么输出不断变化。任何帮助将不胜感激。提前致谢!
编辑:不同的输出确实倾向于遵循某种模式。似乎每五次就循环一次。
慕侠2389804
相关分类