1

I have an array with 9 items and i want to choose only 5 in a random way my array have questions for a quizz and i want that the questions be different

i already tried but my code gives a minimum of 5 questions but sometimes appears 5 7 or 8 when i refresh the page. i think my code is giving a minium of 5 and a max of 8 questions

export let questions = []

if (localStorage.questions){
    questions = JSON.parse(localStorage.questions)
}

else {

    const question1 = new Question (
    "1",
    "Qual é a capital de Portugal?",
    ["Porto","Lisboa","Braga","Guimarães"],
    "Lisboa",
    "10",
    "",
    "1"
    )

    const question2 = new Question(
    "2",
    "Que cidade é conhecida como cidade invicta?",
    ["Viseu","Évora","Santarém","Porto"],
    "Porto",
    "10",
    "",
    "1"
    )

    const question3 = new Question(
    "3",
    "Que cidade é conhecida como cidade berço de Portugal?",
    ["Braga","Leiria","Guimarães","Bragança"],
    "Guimarães",
    "10",
    "",
    "1"
    )

    const question31 = new Question(
    "31",
    "Qual é a capital do Minho?",
    ["Porto","Guimarães","Braga","Vila-Real"],
    "Braga",
    "10",
    "",
    "1"
    )

    const question32 = new Question(
    "32",
    "Quantos habitantes tem a cidade do Porto?",
    ["214349","200350","210323","215000"],
    "214349",
    "10",
    "",
    "1"
    )

    const question33 = new Question(
    "33",
    "Em que cidade nasceu o primeiro rei de Portugal?",
    ["Porto","Lisboa","Guimarães","Bragança"],
    "Guimarães",
    "10",
    "",
    "1"
    )


    const question34 = new Question(
     "34",
    "Os barcos do rabelo são uma caracteristica de que cidade?",
    ["Porto","Lisboa","Guimarães","Bragança"],
    "Porto",
    "10",
    "",
    "1"
    )

    const question35 = new Question(
    "35",
    "Qual destas cidades fica no Algarve?",
    ["Porto","Faro","Guimarães","Bragança"],
    "Faro",
    "10",
    "",
    "1"
    )

    const question36 = new Question(
    "36",
    "Qual destas cidades fica no centro de Portugal?",
    ["Porto","Faro","Aveiro","Bragança"],
    "Aveiro",
    "10",
    "",
    "1"
    )


    questions.push(question1,question2,question3,question31,question32,question33,question34,question35,question36)
    localStorage.setItem("questions", JSON.stringify(questions))

}

 export function choose() {  // funcao para randomizar as perguntas no quiz

    let num = Math.floor(Math.random() * questions.length - 6);
    let name = questions.splice(num,4);
    questions.push(name)
 }

then i render my questions this way


renderQuestions();


function renderQuestions() {
    choose();

    let result1 = ""

    for (const question of questions) {

        if(question.level === "1")  {

   console.log("level1")
        // gerar estrutura


        result1 += `
    <div>
    <p id="question">${question.description}</p>
    <input type="radio" id="raBtn" value="${question.options[0]}" name="${question.id}">${question.options[0]}<br>     
    <input type="radio" id="raBtn" value="${question.options[1]}" name="${question.id}" >${question.options[1]}<br>
    <input type="radio" id="raBtn" value="${question.options[2]}" name="${question.id}">${question.options[2]}<br>
    <input type="radio" id="raBtn" value="${question.options[3]}" name="${question.id}">${question.options[3]}<br>
    <font size="1">Pontos : ${question.points}</font>

    </div>
    `
        // name=question.id diferencia as questoes pelo id para que quando selecionarmos o radio button nao tirar a opçao nas outras questoes

        myQuestions.innerHTML = result1;
        }



}


}
  • 1
    Better target actually [How to efficiently randomly select array item without repeats?](https://stackoverflow.com/questions/17891173/how-to-efficiently-randomly-select-array-item-without-repeats) – Liam Jun 20 '19 at 11:17
  • 1
    I mean the overreaching question is a duplicate but his current problem right now is not the topic. – claasic Jun 20 '19 at 11:27
  • Did he chose the title badly - yes. But it is clear from reading 20s into his post that this is either a programming error either due to splice or async programming and not really OP's goal to get a straight up solution to his title. How the hell did this get so many duplicate votes. – claasic Jun 20 '19 at 11:42

1 Answers1

1

Your choose() function was kind of messed up. Check this out, commented:

let questions = ['a?','b?','c?','d?','e?','f?','g?','h?']
let randomIndexesOfQuestions = []
let questionsToAsk = [];

function choose() {
  // choose a random number between 0 and (array.length - 1).
  let randomIndex = Math.round(Math.random() * (questions.length - 1));

  // if number was already picked, don't pick it again.
  if (!randomIndexesOfQuestions.includes(randomIndex)) {
    randomIndexesOfQuestions.push(randomIndex)
  }

  // if after the number was picked the length of the random indexes is 5, pick the questions with those indexes and add them to the new array.
  if (randomIndexesOfQuestions.length === 5) {
    questionsToAsk = randomIndexesOfQuestions.map(indexOfQuestion => questions[indexOfQuestion])
  } else {
    // if there are not 5 questions picked yet, pick again.
    choose();
  }
}

choose();
console.log(questionsToAsk)
Smytt
  • 364
  • 1
  • 11