-1

I am trying to get this code to pick out 4 keys at random, and then write them to the console using a 'foreach' loop. Instead of picking out a random selection for each iteration, it just picks one of the keys at random and writes it to the console 4 times. Here is the code:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace ListPractice
{
    public class DictionaryData
    {           
        public static void GetRandomKey()
        {
            Dictionary<string, int[]> QandA_Dictionary = new Dictionary<string, int[]>();
            QandA_Dictionary.Add("What is 1 + 1?", new int[] { 1, 2, 3, 4 });
            QandA_Dictionary.Add("What is 1 + 2?", new int[] { 1, 2, 3, 4 });
            QandA_Dictionary.Add("What is 1 + 3?", new int[] { 1, 2, 3, 4 });
            QandA_Dictionary.Add("What is 1 + 4?", new int[] { 2, 3, 4, 5 });

            List<string> keys = new List<string>(QandA_Dictionary.Keys);

            foreach (var element in keys)
            {
                Random rand = new Random();
                string randomKey = keys[rand.Next(keys.Count)];
                Console.WriteLine(randomKey);
            }
            Console.ReadKey();
        }

        public static void Main(string[] args)
        {
            GetRandomKey();
        }

    }
}
sean
  • 11
  • 3

1 Answers1

1

It randomizes once because you keep creating a new instance of the Random class. Every time you initialize an instance of the Random class with no seed, it will automatically use the clock's current tick count as its seed. Due to how fast a loop usually iterates it will be done in one to a few milliseconds, meaning your Random will pretty much always have the same seed.

Declaring the Random outside your loop will result in a seed change every time you use it, thus you won't get the same number(s) over and over again:

Random rand = new Random();
foreach (var element in keys)
{
    string randomKey = keys[rand.Next(keys.Count)];
    Console.WriteLine(randomKey);
}
Visual Vincent
  • 18,045
  • 5
  • 28
  • 75
  • That is pretty interesting. I am still learning. Thanks for your help. – sean Jul 17 '16 at 22:00
  • @sean : No problem, I'm glad I could help you! There's even more information to read on [**the MSDN documentation about it**](https://msdn.microsoft.com/en-us/library/h343ddh9(v=vs.110).aspx). – Visual Vincent Jul 17 '16 at 22:14