Reputation: 13
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.
Upvotes: 1
Views: 123
Reputation: 33486
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.
Upvotes: 1