为了账号安全,请及时绑定邮箱和手机立即绑定

即使我没有更改任何内容,我的 go 代码也会返回不同的结果

即使我没有更改任何内容,我的 go 代码也会返回不同的结果

Go
牧羊人nacy 2023-07-04 14:49:01
我正在研究将罗马数字解码为 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 回答

?
慕侠2389804

TA贡献1719条经验 获得超6个赞

如果后来有其他人出现,我没有意识到 go 映射不能保证迭代顺序,因此需要一个单独的数据结构。

查看完整回答
反对 回复 2023-07-04
  • 1 回答
  • 0 关注
  • 78 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信