How to order questions randomly?

Asked

Viewed 106 times

0

I’m finishing a project of Quiz Unity game in C#, let me try to explain what I need, I already ask the random questions, but I want the answers to be displayed at random as well. I have a list of 5 questions, each question has 4 alternatives, the questions are selected by an ID. today the code is so:

            pergunta.text = perguntas[idPergunta];
            respostaA.text = alternativa1[idPergunta];
            respostaB.text = alternativa2[idPergunta];
            respostaC.text = alternativa3[idPergunta];
            respostaD.text = alternativa4[idPergunta];

in the fieldA, I want you to receive a random value between alternative1, alternative2, alternative3, alternative4. for example, Random says that in the field replyA.text receives alternative4, so respotaB.text cannot receive this alternative, Random would have to generate another alternative.

2 answers

3


 using System.Collections.Generic;

[...]

List<string> temp = new List<string>();

temp.Add(alternativa1[idPergunta]);
temp.Add(alternativa2[idPergunta]);
temp.Add(alternativa3[idPergunta]);
temp.Add(alternativa4[idPergunta]);

var r = new Random();

var c = r.Next(4);
respostaA.text = temp[c];
temp.RemoveAt(c);

c = r.Next(3);
respostaB.text = temp[c];
temp.RemoveAt(c);

c = r.Next(2);
respostaC.text = temp[c];
temp.RemoveAt(c);

respostaD.text = temp[0];

2

The most practical method:

void Shuffle<T>(List<T> objetos)
{
  Random r = new Random();
  objetos.Sort(Comparer<T>.Create((a,b) => { return r.NextDouble() > 0.5 ? 1 : -1; }));
}

So:

List<string> objetos = new List<string>();

objetos.Add("A");
objetos.Add("B");
objetos.Add("C");
objetos.Add("D");
objetos.Add("E");
objetos.Add("F");
Shuffle(objetos);

foreach (var item in objetos)
{
    Debug.WriteLine(item.ToString());
}

  • This code can be simplified: objects. Sort(Comparer<T>. Create((a, b) => r.Next(2)-1));

  • With this optimization you gain about 3~5 nano seconds per comparison. It is a practical solution and not the best one. Surely it is possible to optimize this further without using the sort algorithm (which is kind of stupid to sort in a LOL scrambled way)

  • I believe the implementation of . Net is a Quick Sort, which is N Log N, but this is easily linearizable.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.