1

So I'm making a site with questions that u need to answer and I want to use the questions in the same order. So how do I use the Math.random() function to randomize my questions, and I don't want to randomize the answers! Please help with this javascript code:

  (function() {
    const myQuestions = [{
            question: "Esimerkki kysymys1",
            answers: {
                a: "Oikein",
                b: "Väärin"
            },
            correctAnswer: "a"
        },
        {
            question: "Esimerkki kysymys2",
            answers: {
                a: "Oikein",
                b: "Väärin"
            },
            correctAnswer: "b"
        },
        {
            question: "Esimerkki kysymys3",
            answers: {
                a: "Oikein",
                b: "Väärin"
            },
            correctAnswer: "a"
        }
    ];

    function Random() {
        var display = document.getElementById("myQuestions");
        var questionAmount = 2;
        for (var i = 0; i < questionAmount; i++) {
            do {
                var randomQuestion = Math.floor(Math.random() * questions.length);
            } while (existingQuestions());

            display.innerHTML += questions[randomQuestion] + '<br>';
            questionTracker.push(randomQuestion);
        }


        function existingQuestions() {
            for (var i = 0; i < questionTracker.length; i++) {
                if (questionTracker[i] === randomQuestion) {
                    return true;
                }
            }
            return false;
        }
    }

    function buildQuiz() {
        // we'll need a place to store the HTML output
        const output = [];

        // for each question...
        myQuestions.forEach((currentQuestion, questionNumber) => {
            // we'll want to store the list of answer choices
            const answers = [];

            // and for each available answer...
            for (letter in currentQuestion.answers) {
                // ...add an HTML radio button
                answers.push(
                    `<label>
     <input type="radio" name="question${questionNumber}" value="${letter}">
      ${letter} :
      ${currentQuestion.answers[letter]}
   </label>`
                );
            }

            // add this question and its answers to the output
            output.push(
                `<div class="slide">
   <div class="question"> ${currentQuestion.question} </div>
   <div class="answers"> ${answers.join("")} </div>
 </div>`
            );
        });

        // finally combine our output list into one string of HTML and put it on the page
        quizContainer.innerHTML = output.join("");
    }

    function showResults() {
        // gather answer containers from our quiz
        const answerContainers = quizContainer.querySelectorAll(".answers");

        // keep track of user's answers
        let numCorrect = 0;

        // for each question...
        myQuestions.forEach((currentQuestion, questionNumber) => {
            // find selected answer
            const answerContainer = answerContainers[questionNumber];
            const selector = `input[name=question${questionNumber}]:checked`;
            const userAnswer = (answerContainer.querySelector(selector) || {}).value;

            // if answer is correct
            if (userAnswer === currentQuestion.correctAnswer) {
                // add to the number of correct answers
                numCorrect++;

                // color the answers green
                answerContainers[questionNumber].style.color = "lightgreen";
            } else {
                // if answer is wrong or blank
                // color the answers red
                answerContainers[questionNumber].style.color = "red";
            }
        });

        // show number of correct answers out of total
        resultsContainer.innerHTML = `${numCorrect} Oikein ${myQuestions.length}`;
    }

    function showSlide(n) {
        slides[currentSlide].classList.remove("active-slide");
        slides[n].classList.add("active-slide");
        currentSlide = n;

        if (currentSlide === 0) {
            previousButton.style.display = "none";
        } else {
            previousButton.style.display = "inline-block";
        }

        if (currentSlide === slides.length - 1) {
            nextButton.style.display = "none";
            submitButton.style.display = "inline-block";
        } else {
            nextButton.style.display = "inline-block";
            submitButton.style.display = "none";
        }
    }

    function showNextSlide() {
        showSlide(currentSlide + 1);
    }

    function showPreviousSlide() {
        showSlide(currentSlide - 1);
    }

    const quizContainer = document.getElementById("quiz");
    const resultsContainer = document.getElementById("results");
    const submitButton = document.getElementById("submit");

    // display quiz right away
    buildQuiz();

    const previousButton = document.getElementById("previous");
    const nextButton = document.getElementById("next");
    const slides = document.querySelectorAll(".slide");
    let currentSlide = 0;

    showSlide(0);

    // on submit, show results
    submitButton.addEventListener("click", showResults);
    previousButton.addEventListener("click", showPreviousSlide);
    nextButton.addEventListener("click", showNextSlide);
})();

I tried to use the Math.random function, but I could not get it to work!

Máté Safranka
  • 4,081
  • 1
  • 10
  • 22
Zami Coskula
  • 53
  • 2
  • 6
  • 1
    You can just [shuffle the array](https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array) – VLAZ May 21 '18 at 14:03
  • just sort the array to start and loop over the array, no need to keep track of what is used. – epascarello May 21 '18 at 14:04

1 Answers1

1

You can shuffle the array myQuestions by calling shuffle(myQuestions) with the shuffle function below (Fisher Yates algorithm, copied from the answer within link).

function shuffle(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
}

Syntax: shuffledArr = shuffle(arr);

Then display them in order (now shuffled). This will spare space complexity in otherwise having to handle a list of already asked questions.

After conversation with OP, here is the full refactored code: https://jsfiddle.net/L0qzdhg0/4/

Sample snippet below: Run multiple times to see different results

function shuffle(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
}

console.log(
shuffle(
[{
            question: "Esimerkki kysymys1",
            answers: {
                a: "Oikein",
                b: "Väärin"
            },
            correctAnswer: "a"
        },
        {
            question: "Esimerkki kysymys2",
            answers: {
                a: "Oikein",
                b: "Väärin"
            },
            correctAnswer: "b"
        },
        {
            question: "Esimerkki kysymys3",
            answers: {
                a: "Oikein",
                b: "Väärin"
            },
            correctAnswer: "a"
        }
    ]
    )
    );
Attersson
  • 4,755
  • 1
  • 15
  • 29