-11

can someone tell me why this doesn't work. I want to display randomly ten chemical elements, but it always displays the same elements. Thanks for help!

        var random = new Random();
        var list = new List<string> { "Hg" , "B", "H", "Mg" };
        int index = random.Next(list.Count);
        for (int i = 0; i < 10; i++) {
            Console.WriteLine(list[index]);
        }
  • 4
    You'll need to generate the random index every iteration of the loop. Move line 3 to inside the loop's scope. – asawyer Sep 26 '19 at 17:22
  • 2
    You never update `index` so it's the same random number that was generated the first time. – Mike G Sep 26 '19 at 17:22
  • Did you try debugging your code? Step through it line by line? Examine the values of the variables at each step? That would have told you what you needed to know - then you wouldn't have to ask a question on Stack Overflow. – mason Sep 26 '19 at 17:25
  • If you don't want to repeat the same element, [randomly sort the list](https://stackoverflow.com/a/1262619/43846) and show the first ten. – stuartd Sep 26 '19 at 17:25
  • 3
    **[How to use the awesome, built-in Step Debugger](https://msdn.microsoft.com/en-us/library/y740d9d3.aspx)** – Ňɏssa Pøngjǣrdenlarp Sep 26 '19 at 17:28
  • `Console.WriteLine(string.Join(", ", Enumerable.Range(0, 10).Select(x => list[random.Next(list.Count)])));` – Rufus L Sep 26 '19 at 17:46

3 Answers3

4

As the commenters said, you need a new random Number every itteration. Just reusing the same one you generated at the start will not do.

    var random = new Random();
    var list = new List<string> { "Hg" , "B", "H", "Mg" };

    for (int i = 0; i < 10; i++) {
        int index = random.Next(list.Count);
        Console.WriteLine(list[index]);
    }

Do not move the Random class instantion itself inside the loop however. It is very important that you do not re-create them, but keep using the same instance. Due to the very nature of Randon Number generation, trying to get more randomness by re-creating them will actually end up giving you the same numbers.

Christopher
  • 9,634
  • 2
  • 17
  • 31
0

The issue is that you have defined the "index" variable outside of your for loop which means it is only being set once.

If you set it inside of your for loop, it will change with each iteration. Try this,

   var random = new Random();
   var list = new List<string> { "Hg" , "B", "H", "Mg" };

   for (int i = 0; i < 10; i++) {
       int index = random.Next(list.Count);
       Console.WriteLine(list[index]);
   }
Darkserum
  • 11
  • 4
0

As said by @asawyer, the code should be:

    var random = new Random();
    var list = new List<string> { "Hg" , "B", "H", "Mg" };
    for (int i = 0; i < 10; i++) 
      Console.WriteLine(list[random.Next(list.Count)]);