dimanche 17 juillet 2016

Why does this method only randomize once, instead of randomize each iteration? [duplicate]

This question already has an answer here:

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();
        }

    }
}




Aucun commentaire:

Enregistrer un commentaire