Skip to the code
+10 XP

#86 Shuffle the Quiz Questions

easy

A quiz app shows its questions in a random order. To make tests repeatable, the random numbers are passed in: randoms holds numbers from 0 (included) to 1 (not included), to be used one at a time, in order.

Write shuffleQuiz(questions, randoms) that returns a new shuffled array using this exact procedure: copy questions; then for i from the last index down to 1, take the next random number r, set j = Math.floor(r * (i + 1)), and swap the items at i and j.

Example 1

Input: questions = ["q1","q2","q3","q4"], randoms = [0.5,0.9,0.1]
Output: ["q2","q1","q4","q3"]

i = 3: j = 2, swap to get q1, q2, q4, q3. i = 2: j = 2, no change. i = 1: j = 0, swap to get q2, q1, q4, q3.

Example 2

Input: questions = ["only"], randoms = []
Output: ["only"]

One question has only one possible order.

Constraints

  • 0 <= questions.length <= 10^5
  • randoms.length === Math.max(0, questions.length - 1)
  • 0 <= randoms[i] < 1
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).