我正在研究將羅馬數字解碼為 10 進制數字的 kata,但我遇到了一個非常奇怪的問題。我遇到的問題是輸出不一致,我不知道為什么。我設置了以下代碼來嘗試克服挑戰(我知道它并不完美;這不是問題):package kataimport "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 := romanfor 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,我只是不確定為什么輸出不斷變化。任何幫助將不勝感激。提前致謝!編輯:不同的輸出確實傾向于遵循某種模式。似乎每五次就循環一次。
- 1 回答
- 0 關注
- 133 瀏覽
添加回答
舉報
0/150
提交
取消