用于循环遍历map的Golang不会返回不一致的值

时间:2018-06-06 09:10:01

标签: go

我正在编写一个概率模型,它将采用任意数量的"结果"然后当一个数字滚动并传递给模型时,正确的"结果"将被退回;

基本上,逻辑是结果图,其中索引表示结果特定的权重。

结果一25% 结果二25% 结果三个50%

这些值将转化为;

outcomes := make(map[int]Outcome)
outcomes[25] = Outcome{"Outcome One", 25}
outcomes[50] = Outcome{"Outcome One", 25}
outcomes[100] = Outcome{"Outcome One", 50}

我有一个函数然后接受一个输入让我们说10,并循环结果直到索引大于输入;

预期

input: 10, output: Outcome{"Outcome One", 25}
input: 30, output: Outcome{"Outcome Two", 25}
input: 60, output: Outcome{"Outcome Two", 50}

然而,在我输入10的单元测试中,我得到了"结果一"和"结果二",我认为问题在于我的for循环。

ProbabilityMatrix_test.go

var outcome1 = Outcome{"Outcome One", 25}
var outcome2 = Outcome{"Outcome Two", 25}
var outcome3 = Outcome{"Outcome Three", 50}

probabilityMatrix := ProbabilityMatrix{}
probabilityMatrix.SetUp()

probabilityMatrix.AddOutcome(outcome1)
probabilityMatrix.AddOutcome(outcome2)
probabilityMatrix.AddOutcome(outcome3)

outcome := probabilityMatrix.RollA(10)

if outcome != outcome1 {
    t.Errorf("%s", probabilityMatrix.Delimiters)
    t.Errorf("incorrect outcome, got %s, expected %s", outcome.Name, outcome1.Name)
}

以下代码返回结果一,大约75%的时间(正确),结果二25%

package RealisticTemperatureGenerator

type Outcome struct {
    Name        string
    Probability int
}

type ProbabilityMatrix struct {
    Delimiters     map[int]Outcome
    DefaultOutcome Outcome
    Total          int
}

func (pm *ProbabilityMatrix) SetUp() {
    pm.Delimiters = make(map[int]Outcome)
    pm.Total = 0
}

func (pm *ProbabilityMatrix) AddOutcome(outcome Outcome) {

    pm.DefaultOutcome = outcome
    currentIndex := outcome.Probability + pm.Total
    pm.Delimiters[currentIndex] = outcome
    pm.Total = currentIndex
}

func (pm *ProbabilityMatrix) RollA(input int) Outcome {
  return pm.WalkDelimiters(input)
}

// Problem Possibly here
func (pm ProbabilityMatrix) WalkDelimiters(input int) Outcome {

  for key, _ := range pm.Delimiters {
      if pm.Delimiters[key].Probability >= input {
        return pm.Delimiters[key]
      }
  }
  return pm.DefaultOutcome
}

1 个答案:

答案 0 :(得分:1)

在golang中循环映射时,返回元素的顺序是随机的。这是行为不一致的原因。请参阅官方博客中的“迭代顺序”:https://blog.golang.org/go-maps-in-action

如果您想要一个稳定的订单,您必须将密钥保存在另一个结构中:

keys := []int{25, 50, 100}

for _, key := range keys {
    if pm.Delimiters[key].Probability >= input {
        return pm.Delimiters[key]
    }
}