1

I'm making a quiz. I try to find a way to generate non repeating random numbers from an array. How can help me?

This is what I have:

questions = ["Q1", "Q2", "Q3", "Q4", "Q5", "Q6", "Q7"]
var randoms001 = Math.floor(Math.random() * questions.length);
mohamed-mhiri
  • 202
  • 3
  • 22
Ruth
  • 11
  • 1
  • Can you provide the language please? Is it `javascript`? – Jose Carlos Ramos Carmenates Feb 07 '20 at 13:48
  • Yes it's javascript, forgot to mention it. – Ruth Feb 07 '20 at 13:54
  • 1
    First shuffle the array, then pick as many entries as you need from the front. Assuming the array has no duplicates then the entries you pick will not repeat. I don't know if Javascript has a built-in shuffle. If not, then write a [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher–Yates_shuffle) method for yourself. – rossum Feb 07 '20 at 14:15

1 Answers1

1

Shuffle the array and loop through it.

var questions = ["Q1", "Q2", "Q3", "Q4", "Q5", "Q6", "Q7"];
var shuffledQuestions = randoSequence(questions);

for(var i = 0; i < shuffledQuestions.length; i++){
  console.log( shuffledQuestions[i].value );
}
<script src="https://randojs.com/1.0.0.js"></script>

I used randojs.com to do the shuffle in a simple and readable way, but feel free to shuffle it yourself if you that's your preference.

If you choose to use randojs, just make sure this is in the head of your html document:

<script src="https://randojs.com/1.0.0.js"></script>
Aaron Plocharczyk
  • 2,776
  • 2
  • 7
  • 15