how can i create random function

Viewed 31

I am creating exam webpage, where from 3 arrays my code can randomly choose from each array 5 exercises. The 3 arrays are 1: easy level, 2: medium level and 3: hard level of exercises. There will be 50 exercises on each array with 3-4 answers. I already have some code, but i only use one array. Can you suggest some ways creating my webpage? Thanks in advance :)

Ps. language of webpage is armenian, sorry if you don't understand)

const paragraph = document.querySelector('#paragraph');

const params = new URLSearchParams(window.location.search);

params.forEach((value)=>{
    paragraph.append(`${value}`);
    paragraph.append(document.createElement("br"));
});

(function(){
    // Functions
    function buildQuiz(){
      // variable to store the HTML output
      const output = [];
  
      // for each question...
      myQuestions.forEach(
        (currentQuestion, questionNumber) => {
  
          // variable to store the list of possible answers
          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';
        }
        // if answer is wrong or blank
        else{
          // color the answers red
          answerContainers[questionNumber].style.color = 'red';
        }
      });
  
      // show number of correct answers out of total
      resultsContainer.innerHTML = `you got ${numCorrect} out of ${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);
    }
  
    // Variables
    const quizContainer = document.getElementById('quiz');
    const resultsContainer = document.getElementById('results');
    const submitButton = document.getElementById('submit');
  
    const myQuestions = [
      {
        question: "Լուծել հավասարումը 3 - x > 1",
        answers: {
          a: "(-∞ ; 2]",
          b: "(2 ; +∞)",
          c: "(-∞ ; 2)",
          d: "[2 ; +∞)"
        },
        
        correctAnswer: "c"
      },
      {
        question: "Շրջանագծի հավասարումն է (x + 2)2 + (y + 1)2 = 13, գտնել շոշափողի թեքությունը",
        answers: {
          a: "-2/3",
          b: "Չգիտեմ",
          c: "5",
          d: "2/3"
        },
        correctAnswer: "a"
      },
      {
        question: "x<sup>2</sup> - 3|x - 2| - 4x = - 6 հավասարումից գտնել x-ը",
        answers: {
          a: "Չգիտեմ",
          b: "4, 0, 3, 1",
          c: "8, 9, 15",
          d: "5"
        },
        correctAnswer: "b"
      },
      {
        question: "hello",
        answers: {
          a: "Չգիտեմ",
          b: "hi",
          c: "duck",
          d: "lol"
        },
        correctAnswer: "b"
      }
    ];
    
      buildQuiz();
  
    const previousButton = document.getElementById("previous");
    const nextButton = document.getElementById("next");
    const slides = document.querySelectorAll(".slide");
    let currentSlide = 0;
  
    showSlide(currentSlide);
  
    submitButton.addEventListener('click', showResults);
    previousButton.addEventListener("click", showPreviousSlide);
    nextButton.addEventListener("click", showNextSlide);
  })();
@import url(https://fonts.googleapis.com/css?family=Work+Sans:300,600);

body{
    font-size: 20px;
    font-family: 'Work Sans', sans-serif;
    color: #333;
  font-weight: 300;
  text-align: center;
  background-color: #f8f6f0;
}
h1{
  font-weight: 300;
  margin: 0px;
  padding: 10px;
  font-size: 20px;
  background-color: #444;
  color: #fff;
  border-radius: 3px;
}
.question{
  font-size: 30px;
  margin-bottom: 10px;
}
.answers {
  margin-bottom: 20px;
  text-align: left;
  display: inline-block;
}
.answers label{
  display: block;
  margin-bottom: 10px;
}
button{
  font-family: 'Work Sans', sans-serif;
    font-size: 22px;
    background-color: #279;
    color: #fff;
    border: 0px;
    border-radius: 3px;
    padding: 20px;
    cursor: pointer;
    margin-bottom: 20px;
}
.in{
  font-family: 'Work Sans', sans-serif;
    font-size: 22px;
    background-color: #fff;
    color: #444;
    border: 0px;
    border-radius: 3px;
    padding: 20px;
    cursor: pointer;
    margin-bottom: 20px;
}
button:hover{
    background-color: #38a;
}
.slide{
  position: absolute;
  left: 0px;
  top: 0px;
  width: 100%;
  z-index: 1;
  opacity: 0;
  transition: opacity 0.5s;
}
.active-slide{
  opacity: 1;
  z-index: 2;
}
.quiz-container{
  position: relative;
  height: 200px;
  margin-top: 40px;
}
.but{
  font-family: 'Work Sans', sans-serif;
    font-size: 22px;
    background-color: #279;
    color: #fff;
    border: 0px;
    border-radius: 3px;
    padding: 20px;
    cursor: pointer;
    margin-bottom: 20px;
}
#paragraph{
  text-align: left;
  background-color: rgba(68, 68, 68, 0.315);
  width: max-content;
  border-radius: 3px;
}
<!DOCTYPE html>
<html lang="hy">
<head>
    <link rel="stylesheet" href="style.css">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>11 քննություն</title>
    <link rel="stylehseet" href="style.css">
</head>
<body>
    <br><h1>Երևանի Գալուստ Գյուլբենկյանի անվան համար 190 ավագ դպրոց
        <br><br>Մաթեմատիկայի առցանց քննություն
        <br><br>11-րդ դասարանի մաթեմատիկա</h1><br>
    <p id="paragraph"></p>
    <div class="quiz-container">
        <div id="quiz"></div>
      </div><br><br><br>
      <button id="previous">Նախորդ խնդիրը</button>
      <button id="next">Հաջորդ խնդիրը</button>
      <button id="submit">Ստուգել պատասխանները</button>
      <div id="results"></div>
    <script src="script11.js"></script>
</body>
</html>

1 Answers

I would suggest to create a js function with 2 parameters. The first parameter is the array with all exercises (easy / medium / hard). Second parameter would be the amount how many results do you want to get. So it would look something like this:

function getRandomExercises(exercises, exerciseAmount) {
  const result = [];
  for(let i = 0; i < exerciseAmount; i++) {
    result.push(exercises[Math.floor(Math.random()*exercises.length)])
  }

  return result;
}

Then you could call the function with the different levels of you app like so:

getRandomExercises(easyExercises, 5);
getRandomExercises(mediumExercises, 5);
getRandomExercises(hardExercises, 5);
Related