1

I am making a STEM game for a school and I'm having it randomly pick question numbers. There are 30 questions but I only want 20 of that 30 to be used. I need it to randomly pick a number from 1-30 (No 0) and set each random number to a certain variable. But I can't figure out how to make it so that it doesn't use the same number twice. Any help?

Heres the code I got so far:

function onLoad() {
 var N1 = Math.floor(Math.random() * 30) + 1;
 var N2 = Math.floor(Math.random() * 30) + 1;
 var N3 = 0;
 var N4 = 0;
 var N5 = 0;
 var N6 = 0;
 var N7 = 0;
 var N8 = 0;
 var N9 = 0;
 var N10 = 0;
 var N11 = 0;
 var N12 = 0;
 var N13 = 0;
 var N14 = 0;
 var N15 = 0;
 var N16 = 0;
 var N17 = 0;
 var N18 = 0;
 var N19 = 0;
 var N20 = 0;
 
 //Make it so each one is checked so that the same question is not used
 //N1 is gonna be the first question and does not need to be check
 //N2-N20 need to make sure they aren't the same as N1-N20
 
 if (N2 == N1) {
  N2 = Math.floor(Math.random() * 30) + 1;
 }
}

I have a good idea of the checker but there is also the chance that if it is the same in the beginning and I have it generate a new number it'll be the same number and mess up the game.

  • 8
    Make an array of the numbers 1 .. 30, shuffle the array, and take the first 20 numbers. – 4castle Nov 10 '17 at 13:38
  • Or make an array of numbers and remove a random element 20 times, setting your variable to the removed value – Nick is tired Nov 10 '17 at 13:39
  • @NickA 10 times* – Rick Nov 10 '17 at 13:40
  • @RickvanOsta no 20, remove as in take, updated to make it more clear – Nick is tired Nov 10 '17 at 13:40
  • But if I make an array of the generated numbers, how would I set each individual number to a variable? – Kyle Wilcox Nov 10 '17 at 13:42
  • 2
    Possible duplicate of [How to randomly generate numbers without repetition in javascript?](https://stackoverflow.com/questions/15585216/how-to-randomly-generate-numbers-without-repetition-in-javascript) – 4castle Nov 10 '17 at 13:44
  • @KyleWilcox Making 20 different variables that are all numbered is a bad idea. Your code will quickly get super messy, and you will have 20 of everything. If you keep the numbers in the array, you can index it, like `N[5]` would get the sixth number. This will allow you to use loops if you want to do something 20 times. – 4castle Nov 10 '17 at 13:47
  • @4castle can you possibly post code because I can't quite figure out how to make the array with random numbers and index it – Kyle Wilcox Nov 10 '17 at 14:07

1 Answers1

1

First, you need to generate an array of the numbers 1-30, then shuffle the array, and then you can retrieve the first 20 numbers in the array.

function getRandomQuestionNumbers() {
  var numbers = [];
  for (var i = 1; i <= 30; i++) {
    numbers.push(i);
  }
  shuffle(numbers);
  return numbers.slice(0, 20);
}  

For a good shuffle function, use one of the top answers to this question.

4castle
  • 32,613
  • 11
  • 69
  • 106