Sakuna Madushanka
Sakuna Madushanka

Reputation: 178

Create a random List from Dictionary in C# including one specific selected Item

I have a Dictionary that includes both key and value as strings. What I'm doing is I stored a word set with definition as Key as the word and definition as value. There are around 100 items in the dictionary. I'm creating a game in unity to select a word from the puzzle and player have to answer for a question that weather the definition is true or false. So now I select the value from whole dictionary which make the probability of getting true as the answer is 1%. I want to select 5 values from the dictionary including the correct answer and select randomly from that list or array.

This is how I initialized my dictionary.

public Dictionary<string, string> def = new Dictionary<string, string>(){
{"word1","definition1"},
{"word1","definition1"},
{"word1","definition1"}...
};

Can anyone help me out to solve this?

Thank you.

Upvotes: 0

Views: 1236

Answers (2)

Sushant Yelpale
Sushant Yelpale

Reputation: 889

Assuming you have options in dictionary up to few thousand.

Dictionary<string, string> options = new Dictionary<string, string>();
options.Add("YourKey", def["YourKey"]);  // Correct Answer

Random r = new Random();
while (options.Count < 5)
{
    int randNum = r.Next(0, def.Count-1);

    if (!options.Keys.Contains(def.ElementAt(randNum).Key))
        options.Add(def.ElementAt(randNum).Key, def.ElementAt(randNum).Value);
}

List<string> OptionsList = options.Select(e=> e.Value).ToList();
// Shuffle OptionsList 

Finally, Shuffle your List using some best algorithms

Upvotes: 1

Kevin
Kevin

Reputation: 2631

Lets say you have 100 items, you could do something like this:

//take six in case one duplicates 
var items = new  List<int>();
items.AddRange(Enumerable.Range(0, 99).OrderBy(i => rand.Next()).Take(6))

//now loop through your items and disregard if duplicated
var words =new List<string>();

foreach(var item in items)
{
     //i'll leave it to you to implement the check...
     words.Add(def.ElementAt(item).Key);
}

Upvotes: 1

Related Questions