C# - 选择随机项列表,概率在开始时几次丢弃1个元素

时间:2017-05-15 08:44:35

标签: c# xml random probability

我的随机部分代码是:

        public Gun GetRandomGun(IEnumerable<Gun> sequence, Random random)
        {
            int totalWeight = sequence.Sum(p => p.Probability);
            int weightedPick = random.Next(totalWeight);
            foreach (var item in sequence)
            {
                if (weightedPick < item.Probability)
                {
                    return item;
                }
                weightedPick -= item.Probability;
            }
            throw new InvalidOperationException("List must have changed...");

所以我正试图通过概率获得随机枪,你可以看到.. 因此,当我在开始时打开程序时,我几次调用命令,我得到相同的枪,然后程序给我随机枪,有时甚至给同样的枪x 2 我该如何解决? 我的XML配置:

    <Gun>
      <GunID>116</GunID>
      <Probability>18</Probability>
    </Gun>
    <Gun>
      <GunID>519</GunID>
      <Probability>5</Probability>
    </Gun>
    <Gun>
      <GunID>363</GunID>
      <Probability>25</Probability>
    </Gun>
    <Gun>
      <GunID>126</GunID>
      <Probability>10</Probability>
    </Gun>
    <Gun>
      <GunID>112</GunID>
      <Probability>15</Probability>
    </Gun>
    <Gun>
      <GunID>297</GunID>
      <Probability>5</Probability>
    </Gun>
    <Gun>
      <GunID>300</GunID>
      <Probability>5</Probability>
    </Gun>
    <Gun>
      <GunID>1041</GunID>
      <Probability>25</Probability>
    </Gun>
    <Gun>
      <GunID>1037</GunID>
      <Probability>25</Probability>
    </Gun>

所以例如当我启动程序并且几次调用命令时,我只获得了id 1041,并且在几次之后我开始获得随机枪,有时当我调用命令2次时,我获得同样的枪,但这不重要 请帮我修复bug,谢谢!

1 个答案:

答案 0 :(得分:0)

存储最后检索到的枪ID,然后检索新枪检查其ID与最后存储的枪ID如果匹配则重新调用该方法。

使用递归函数。