0

I have a list of a custom class, (called enemy), named enemyList. I use a foreach loop. Inside, I generate a random number between 1 and 200,000. Then I save it to a list outside of the foreach loop:

  try
  {
  List<int> randoms = new List<int>();
  foreach (enemy m in enemyList)
  {
     Random r = new Random();
     int i = r.Next(1, 2000);
     randoms.Add(i);
  }

Then, when that is done, under the foreach loop, I do this:

int highest = randoms.Max();
int rate = -1;

Next, I use another foreach loop to figure out which value in randoms equals the highest number.

  foreach (int number in randoms)
   {
       rate++;
       if (highest == number)
       {
           return rate;
       }
   }
   }
   catch (Exception)
   {

     return 0;
   }

When I run it, it displays which item is the highest, (example: if it is the first in the randoms list, then display 0). But for some reason, it always returns 0. But if I walk through the code, it works properly. Can anyone explain why this happens so I can fix it?

Servy
  • 202,030
  • 26
  • 332
  • 449
  • 6
    Try declaring `r = new Random()` outside the loop. Each time you instantiate a new random, it reseeds. – John Wu Apr 17 '18 at 21:27
  • 2
    To clarify a little, new Random() re-seeds with the current timestamp. If the loop runs at speed, you are easily re-seeding with the same timestamp every time, so all the random numbers will be the same. – glenebob Apr 17 '18 at 21:32

1 Answers1

-3

Are you trying to select a random item from your enemies list?

If so, you could just do something like this:

var rng = new Random();
var randomEnemy = enemyList[ rng.Next( enemyList.Count ) ];

If you are doing this rapidly you would want to declare your random number generator somewhere else so it isn't reseeding and constantly selecting the same value.

JohnStrom
  • 89
  • 1
  • 1
  • 7
  • What? I have never seen code like that. =-( –  Apr 17 '18 at 21:47
  • In the above case, `var randomEnemy = enemyList[ rng.Next( enemyList.Count ) ];` will return a random enemy. `rng.Next( someInt )` will return a random positive integer that is less than someInt. Then you can just use that randomly generated integer to directly access the enemy from the enemyList. – JohnStrom Apr 17 '18 at 22:06