How to make the questions random without repeating and run a specific number of questions?

Asked

Viewed 896 times

2

I wanted to make the questions were random but not repeated running the 6 questions that make up each theme of my QUIZ-style game, if they know an easy method for my problem.

I tried several researches and did not get anything maybe because I did not know apply the most advanced knowledge of the staff, please if you can explain in detail I would be very grateful because I am beginner. Thanks for your attention and understanding. Follow my script I use for answers.

using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.SceneManagement;

public class responder : MonoBehaviour {


private int idTema;
public Text pergunta;
public Text respostaA;
public Text respostaB;
public Text respostaC;
public Text respostaD;
public Text InfoRespostas;
public AudioSource m_Audiosource;   

public string[] perguntas;          //alterei aqui string[] perguntas;  armazena todas as perguntas
public string[] alternativaA;       //armazena todas as alternativas A
public string[] alternativaB;       //armazena todas as alternativas B
public string[] alternativaC;       //armazena todas as alternativas C
public string[] alternativaD;       //armazena todas as alternativas D
public string[] corretas;           //armazena todas as alternativas corretas


private int idPergunta;
private float acertos;
private float questoes;
private float media;
private int notaFinal;

void Start () 
{

    idTema = PlayerPrefs.GetInt ("idTema");
    idPergunta = 0;
    questoes = perguntas.Length;

    pergunta.text = perguntas [idPergunta];
    respostaA.text = alternativaA [idPergunta];
    respostaB.text = alternativaB [idPergunta];
    respostaC.text = alternativaC [idPergunta];
    respostaD.text = alternativaD [idPergunta];

    InfoRespostas.text = "Respondendo "+(idPergunta + 1).ToString()+" de "+questoes.ToString()+" perguntas.";
}



public void resposta (string alternativa)
{
    if (alternativa == "A"){
        if (alternativaA [idPergunta] == corretas [idPergunta])
        {
            acertos += 1;
            m_Audiosource.Play ();
        }
        } 

    else if (alternativa == "B") {
        if (alternativaB [idPergunta] == corretas [idPergunta])
        {
            acertos += 1;
            m_Audiosource.Play ();
        }
        }

    else if (alternativa == "C") {
        if (alternativaC [idPergunta] == corretas [idPergunta])
        {
            acertos += 1;
            m_Audiosource.Play ();
        }
        } 

    else if (alternativa == "D") {
        if (alternativaD [idPergunta] == corretas [idPergunta])

        {
            acertos += 1;
            m_Audiosource.Play ();
        }
        }

    proximaPergunta ();
        }


void proximaPergunta()
    {

    idPergunta += 1;  // se fosse 20 questões aqui seria 19
    if(idPergunta <= (questoes-1))
    {
    pergunta.text = perguntas [idPergunta];
    respostaA.text = alternativaA [idPergunta];
    respostaB.text = alternativaB [idPergunta];
    respostaC.text = alternativaC [idPergunta];
    respostaD.text = alternativaD [idPergunta];

    InfoRespostas.text = "Respondendo "+(idPergunta + 1).ToString()+" de "+questoes.ToString()+" perguntas.";

    }

else
        {
        {
            media = 6 * (acertos / questoes);  //calcula a media com base no percentual de acerto
            notaFinal = Mathf.RoundToInt(media); //calcula a nota para o proximo inteiro, segundo a regra da matematica

        if(notaFinal > PlayerPrefs.GetInt("notaFinal"+idTema.ToString()))
        {
            PlayerPrefs.SetInt ("notaFinal" + idTema.ToString (), notaFinal);
            PlayerPrefs.SetInt("acertos"+idTema.ToString(), (int) acertos);
        }

            PlayerPrefs.SetInt ("notaFinalTemp" + idTema.ToString (), notaFinal);
            PlayerPrefs.SetInt("acertosTemp"+idTema.ToString(), (int) acertos);

            SceneManager.LoadScene ("notaFinal");
        }
        }
}

}

2 answers

1

Excellent explanation, but lacked to explain for the most inattentive that arrays indices begin at 0 and not at 1. That is, an array with 5 values the last Indice will be the number 4.

array(0)="1a pergunta";
array(1)="2a pergunta";
array(2)="3a pergunta";
array(3)="4a pergunta";
array(4)="5a pergunta";

And it is necessary to take this into account in the code that generates the list of questions sorted randomly.

  • Thank you for clarifying :)

0


As I was able to understand your questions are stored in a array public string[] perguntas; and soon the questions are accessed through their indexes. I will then help you create an algorithm that automatically generates integer values for you to use in your code.

HOW TO GENERATE RANDOM NUMBERS

The secret then is to use the Class Random to generate random values and through these values choose the question you want. To declare a Random do so:

int valorMin = 0;
int valorMax = 5;
Random random = new Random();
int valorRandomico = random.Next(valorMin, valorMax+1);

That way you’ll have a value like whole assigned to the variable valorRandomico between 0 and 5. It is important to note that I am making an addition in valorMax so that the randomly generated value is actually between 0 and 5.

RANDOM NUMBERS THAT DO NOT REPEAT

Now let’s create an algorithm that returns random values that never repeat. To do this we will use a List<> so that whenever a new value is generated we add the same.

To declare a list do so:

static List<int> listaPerguntasFeitas = new List<int>();

Now what we need to do is create a function that checks if a certain value already exists registered in the list.

static bool ContainsItem(int _numero)
{
    if (listaPerguntasFeitas.Contains(_numero))
    {
        return true;
    }
    else
    {
        return false;
    }
}

We will also create a function to generate the values randomly, but this will not verify yet if the number generated by it already exists. Just do the rough work.

static int RandomNumber(int _min, int _max)
{
    Random random = new Random();
    return random.Next(_min, _max+1);
}

That way we have in hand the sketch to create our non-repeating number generator. The following code will finally generate the random questions. We will then create a new function for this task:

static int GerarPergunta(int _quantidaDePerguntasCadastradas)
{
    bool loop = true;
    while (loop)
    {
        int numer = RandomNumber(1, _quantidaDePerguntasCadastradas); // Gera valor aleatório.

        // Se o valor não existe cadastra valor gerado.
        if (ContainsItem(numer) != true)
        {
            listaPerguntasFeitas.Add(numer);
            return numer;
        }

        if (listaPerguntasFeitas.Count >= _quantidaDePerguntasCadastradas)
        {
            loop = false;
        }
    }

    return 0;
}

This function checks if the value has already been generated previously in our list and otherwise it registers the new value generated and returns us through the return function. We note that the function receives the parameter _quantidaDePerguntasCadastradas The purpose of this is to identify if we have already exceeded the limit of questions generated. Don’t worry if it seems too obscure and confusing at the moment you will surely understand better now that we will finally use it.

In the main method we will finally use our Question generator:

static void Main(string[] args)
{
    //Menu();
    Console.WriteLine("1 Valor gerado: " + GerarPergunta(5));
    Console.WriteLine("2 Valor gerado: " + GerarPergunta(5));
    Console.WriteLine("3 Valor gerado: " + GerarPergunta(5));
    Console.WriteLine("4 Valor gerado: " + GerarPergunta(5));
    Console.WriteLine("5 Valor gerado: " + GerarPergunta(5));

    // Após a função GerarPergunta ser executada 5 vezes o resultado será sempre 0
    Console.WriteLine("\n");
    Console.WriteLine("6 Valor gerado: " + GerarPergunta(5));
    Console.WriteLine("7 Valor gerado: " + GerarPergunta(5));
    Console.WriteLine("8 Valor gerado: " + GerarPergunta(5));

    Console.ReadKey();
}

Let’s compile the code and see the result on the Console screen: Print mostrando o resultado da execução As we can observe after we call the method Gerarpergunta 5 times the next time he always returned 0 informing us that it has already exceeded the stipulated amount.

We could also create a function to return the current list size:

static int TamanhoAtualDaLista()
{
    return listaPerguntasFeitas.Count;
}

This way it will be possible to create an if before trying to generate any question. In the code snippet below a loop will generate questions automatically until the amount of values predefined in the method is exceeded Gerarpergunta(); which in this case is five (5).

static void Main(string[] args)
{
    int minhaQuantidadeDePerguntas = 5;

    bool loop = true;
    int cont = 1;

    while (loop)
    {
        Console.WriteLine(cont + " Valor gerado: " + GerarPergunta(minhaQuantidadeDePerguntas));
        cont++;
        if (TamanhoAtualDaLista() >= minhaQuantidadeDePerguntas)
        {
            loop = false;
        }
    }

    Console.ReadKey();
}

Let’s compile the code again to see the result on the Console screen: Print mostrando o resultado da execução

The complete code for use is here:

static List<int> listaPerguntasFeitas = new List<int>();

static int RandomNumber(int _min, int _max)
{
    Random random = new Random();
    return random.Next(_min, _max+1);
}

static bool ContainsItem(int _numero)
{
    if (listaPerguntasFeitas.Contains(_numero))
    {
        return true;
    }
    else
    {
        return false;
    }
}

static int TamanhoAtualDaLista()
{
    return listaPerguntasFeitas.Count;
}

static int GerarPergunta(int _quantidaDePerguntasCadastradas)
{
    bool loop = true;
    while (loop)
    {
        int numer = RandomNumber(1, _quantidaDePerguntasCadastradas); // Gera valor aleatório.

        // Se o valor não existe cadastra valor gerado.
        if (ContainsItem(numer) != true)
        {
            listaPerguntasFeitas.Add(numer);
            return numer;
        }

        if (TamanhoAtualDaLista() >= _quantidaDePerguntasCadastradas)
        {
            loop = false;
        }
    }

    return 0;
}

static void Main(string[] args)
{
    int minhaQuantidadeDePerguntas = 5;

    bool loop = true;
    int cont = 1;

    while (loop)
    {
        Console.WriteLine(cont + " Valor gerado: " + GerarPergunta(minhaQuantidadeDePerguntas));
        cont++;
        if (TamanhoAtualDaLista() >= minhaQuantidadeDePerguntas)
        {
            loop = false;
        }
    }

    Console.ReadKey();
}
  • Now in your code instead of question.text = questions [idPergunta]; you can use question.text = questions[Gerarpergunta(questions. Length)];

  • questions. Length returns the number of questions you have registered or the number of indexes. If you have any questions regarding the use of Length access official documentation link: https://msdn.microsoft.com/pt-br/library/system.array.length(v=vs.110). aspx

  • A big hug, any doubt I’m willing to help you.

  • 1

    I advise you to do the [tour] to understand how the site works, see also How to format questions and answers

  • Thank you @Barbetta in fact I could see that you have had work editing my messages. I will do it soon. rsrsrs

  • It would be interesting to change the title of the question to: HOW TO GENERATE RANDOM VALUES THAT DO NOT REPEAT?

  • @Guilhermelima I wanted to thank you immensely you currently I am traveling when I get home I will do it, But for the explanations you’ve made, I’m going to be able to do it, and I wanted to thank you for the patience you’ve had to explain the codes so well, and I can’t find a lot of people willing to take a little bit of your time to teach other people. Mt thanks.I will return to the post saying if it went all right. Thanks again. Hug and stay with God.

  • @Guilhermelima tried to use the code but the Random. Next does not work I know why

  • @Guilhermelima and neither the Console.Writeline and the Console.Readkey :(

  • The Gerarpergunta function had an error! The error was this: int numer = Randomnumber(1, 5);

  • To troubleshoot the error do this: int numer = Randomnumber(1, _quantidaDesurveysCadastradas); // Generates random value.

  • @Guilhermelima o Random. Next is still not working and so is Write line and Console.Redkey. Do you have to access any specific library? I didn’t put the script in the start, there’s some problem?

  • @The libraries I use are: using Unityengine; using Unityengine.UI; using System.Collections; using System.Collections.Generic; using Unityengine.Scengemeemanant;

Show 8 more comments

Browser other questions tagged

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