How to ask the questions to be random without repeating themselves and running a specific number of questions?

2

I wanted to make the questions random, but they would not repeat the 6 questions that make up each QUIZ-style game topic, if they knew of an easy method for my problem.

I tried several searches and I did not get anything, maybe because I did not know how to apply the most advanced knowledge of the staff, please if you can explain in detail I would be very grateful because I am a beginner. Thank you in advance for your attention and understanding. Here is my script that 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");
        }
        }
}

}

    
asked by anonymous 24.05.2018 / 17:04

2 answers

0

As I was able to understand your questions are stored in 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 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);

In this way you will have a integer value 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 fact between 0 and 5.

RANDOM NUMBERS 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 value.

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 whether a given value already exists in the list.

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

Let's also create a function to randomly generate the values, but it will not verify yet if the number it generates already exists. It just does the rough work.

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

In this way we have in hand the sketch to create our generator of non-repeated numbers. The following code will finally generate generating random questions. We will then create a new role 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 whether the value has already been generated previously in our list and otherwise it registers the new generated value and returns us through return of the function. We can notice that the function receives the parameter _quantidaDePerguntasCadastradas . The purpose of this is to identify if we already populate the generated questions limit. Do not worry if this seems too dark and confusing at the moment you certainly understood 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: AswecanseeaftercallingtheGenerateQuestionmethod5timesthenextfewtimesitalwaysreturned0tellingusthatithasalreadyexceededthestipulatedamount.

Wecouldalsocreateafunctiontoreturnthecurrentsizeofthelist:

staticintTamanhoAtualDaLista(){returnlistaPerguntasFeitas.Count;}

Inthiswayyoucancreateanifbeforetryingtogenerateanyquestion.Inthefollowingcodesnippet,anirarloopwillautomaticallygeneratequestionsuntilitpopsuptheamountofdefaultvaluesintheGenerateQuestion()method,whichinthiscaseisfive(5).

staticvoidMain(string[]args){intminhaQuantidadeDePerguntas=5;boolloop=true;intcont=1;while(loop){Console.WriteLine(cont+" Valor gerado: " + GerarPergunta(minhaQuantidadeDePerguntas));
        cont++;
        if (TamanhoAtualDaLista() >= minhaQuantidadeDePerguntas)
        {
            loop = false;
        }
    }

    Console.ReadKey();
}

We will compile the code again to see the result on the Console screen:

Thecompletecodeforuseishere:

staticList<int>listaPerguntasFeitas=newList<int>();staticintRandomNumber(int_min,int_max){Randomrandom=newRandom();returnrandom.Next(_min,_max+1);}staticboolContainsItem(int_numero){if(listaPerguntasFeitas.Contains(_numero)){returntrue;}else{returnfalse;}}staticintTamanhoAtualDaLista(){returnlistaPerguntasFeitas.Count;}staticintGerarPergunta(int_quantidaDePerguntasCadastradas){boolloop=true;while(loop){intnumer=RandomNumber(1,_quantidaDePerguntasCadastradas);//Geravaloraleatório.//Seovalornãoexistecadastravalorgerado.if(ContainsItem(numer)!=true){listaPerguntasFeitas.Add(numer);returnnumer;}if(TamanhoAtualDaLista()>=_quantidaDePerguntasCadastradas){loop=false;}}return0;}staticvoidMain(string[]args){intminhaQuantidadeDePerguntas=5;boolloop=true;intcont=1;while(loop){Console.WriteLine(cont+" Valor gerado: " + GerarPergunta(minhaQuantidadeDePerguntas));
        cont++;
        if (TamanhoAtualDaLista() >= minhaQuantidadeDePerguntas)
        {
            loop = false;
        }
    }

    Console.ReadKey();
}
    
25.05.2018 / 11:31
1

Excellent explanation, but lack explained to the most inattentive that the indices of the arrays start at 0 instead of 1. That is, an array with 5 values the last index will be number 4.

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

And you need to take this into account in the code that generates the randomly ordered list of questions.

    
25.05.2018 / 15:01