Click here to Skip to main content
15,886,518 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am trying to create an application in which I will be offered three answer options (radiobuttons) one will be correct (assigned from the result) but the other two should be randomly generated and different from the correct. It occurred to me to add the correct result to the worksheet and then compare the random number with the correct one and add it to the list as well. Same with the third.


EDIT:
I am trying to create an application in which I will be offered three answer options (radiobuttons). I tried to compile a code that adds random numbers to the list of three answers (one correct, two wrong) but this code generates only the correct answer and two zeros.

What I have tried:

C#
private int wrongResult;
private int failResult;
public void shuffleText()
{
    string wrongResultT;
    string failResultT;
    addToList(wrongResult, failResult);
    wrongResultT = wrongResult.ToString();
    failResultT = failResult.ToString();
    List<string> list = new List<string> { result.Text, wrongResultT, failResultT};
    var rand = new Random();
    var shuffleText = list.OrderBy(x => rand.Next(list.Count)).ToList();
    var radioButtons = new[] { firstOption, secondOption, thirdOption };
    for (int i = 0; i < radioButtons.Length; i++)
       {
        radioButtons[i].Content = shuffleText[i];
       }
}

private void addToList(int wrongResult, int failResult)
{
    int resultNumber;
    failResult = number.Next(1, maxValue);            
    resultNumber = Int32.Parse(result.Text);
    var rtnlist = new List<int> { resultNumber};
    if (failResult != resultNumber)
    {
        rtnlist.Add(failResult);
    }
    wrongResult = number.Next(1, maxValue);   
    if (wrongResult != resultNumber)
    {
        rtnlist.Add(wrongResult);
    }
}



I'm just not sure how to do it. Can anyone advise me?
Posted
Updated 13-Jun-21 21:56pm
v3

1 solution

Simplest way is to make a generic method which accepts a list and "shuffles" them: place all the questions (correct and incorrect) in a List and pass it to the method.

C#
private List<T> Shuffle<T>(List<T> input)
    {
    List<T> results = new List<T>(input.Count);
    List<T> working = new List<T>(input);
    while (working.Count > 0)
        {
        int index = rand.Next(working.Count);
        T random = working[index];
        results.Add(random);
        working.Remove(random);
        }
    return results;
    }
private static Random rand = new Random();
 
Share this answer
 
v3
Comments
Member 15170612 11-Jun-21 7:07am    
Thank you for advice!
OriginalGriff 11-Jun-21 8:11am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900