lundi 15 mai 2017

C# - Selecting random item for list with Probability dropping 1 element few times at the start

My random part code is :

        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...");

So I am trying to get random gun with Probability as you can see.. So when I open the program at the start when I am calling the command few times I am getting the same gun and after that the program is giving me random guns and sometimes even giving the same gun x 2 How can I fix it? My XML config:

    <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>

So for example when I am starting the program and calling the command few times I am getting only id 1041 for example and after a few times I am starting to get random guns and sometimes when I am calling the command 2 times I am getting the same gun but this is less important Please help me fixing the bug, Thanks!




Aucun commentaire:

Enregistrer un commentaire