HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptMinor

Generate a series of random integers between 1 and 10

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
randomgeneratebetweenandseriesintegers

Problem

Is there a better way of generating a series of unique and random integers between 1 and 10 in JavaScript (ES6)?

const ran = [];

while (ran.length < 10) {
  x = Math.floor((Math.random() * 10) + 1);
  if (!ran.includes(x)) {
    ran.push(x);
  }
}
console.log(ran);

Solution

Your code could potentially run forever - in theory, it could randomly pick the same number again and again and again. Probably won't, but the point is that the code may take a long time to run.

A simpler approach is to generate the numbers 1-10, and then shuffle them, Fisher-Yates style. Something like:

var numbers = new Array(10),
    shuffled = [];

// fill one array with the numbers 1-10
numbers = numbers.fill(1).map((_, i) => i + 1);

// shuffle by taking a random element from one array
// and pushing it to the other array
while (numbers.length) {
  let idx = numbers.length * Math.random() | 0; // floor trick
  shuffled.push(numbers[idx]);
  numbers.splice(idx, 1);
}

console.log(shuffled);


(The "floor trick" works by using bitwise OR. Now, bitwise OR zero does actually do anything, but all JavaScript bitwise operations interpret their operands to 32-bit integers, so it's like casting to an int, discarding decimals - i.e. it floors the number.)

Code Snippets

var numbers = new Array(10),
    shuffled = [];

// fill one array with the numbers 1-10
numbers = numbers.fill(1).map((_, i) => i + 1);

// shuffle by taking a random element from one array
// and pushing it to the other array
while (numbers.length) {
  let idx = numbers.length * Math.random() | 0; // floor trick
  shuffled.push(numbers[idx]);
  numbers.splice(idx, 1);
}

console.log(shuffled);

Context

StackExchange Code Review Q#153092, answer score: 4

Revisions (0)

No revisions yet.