2

I'm trying to generate an array of random numbers in ES6 - numbers should not be repeated.

Currently, my function generates an array of random numbers, but they are repeating:

winArray = [...Array(6)].map(() => Math.floor(Math.random() * 53));

Here is non-ES6 solution that I've found: Non-ES6 solution

This solution with Set is not running in a for-loop:

for (let i = 1; i <= draws; i += 1) {
      // Generating a random array of 6 number

      const winArray = new Set();
      while (winArray.size < 6) winArray.add(Math.floor(Math.random() * 53));
}
Leocete
  • 195
  • 2
  • 15

3 Answers3

5

You could take a Set and fill this set until the wanted size.

var numbers = new Set;

while (numbers.size < 6) numbers.add(Math.floor(Math.random() * 53));

console.log(...numbers);

For getting more numbser sets, you could take an empty set for each draw.

var numbers,
    draws = 5,
    i;

for (i = 0; i < draws; i++) {
    numbers = new Set;
    while (numbers.size < 6) numbers.add(Math.floor(Math.random() * 53));

    console.log(...numbers);
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • I'm trying to use this code in the for loop, but it looks like this approach is not working in for loop – Leocete Mar 20 '19 at 20:59
  • a for loop needs only the comparison part. please see edit. – Nina Scholz Mar 20 '19 at 21:02
  • I mean the for loop outside an array generation :) please, take a look at the edited post – Leocete Mar 20 '19 at 21:57
  • i dont understand what you like to get. btw, `winArray` is a set, not an array. why do you have a for loop. what is it for? – Nina Scholz Mar 20 '19 at 22:01
  • I'm creating a lottery app. For-loop iterates through each drop and create a unique array of numbers for each draws. Does that make sense to you? – Leocete Mar 20 '19 at 22:06
3

A Set will only allow unique properties (no duplicates).

let winArray = [...Array(6)].map(() => Math.floor(Math.random() * 53));

winArray = [...new Set(winArray)]

console.log(winArray)
Francis Leigh
  • 1,870
  • 10
  • 25
0

Here's a solution that shuffles a list of unique numbers (no repeats, ever).

for (var a=[],i=0;i<100;++i) a[i]=i;

function shuffle(array) {
  var tmp, current, top = array.length;
  if(top) while(--top) {
    current = Math.floor(Math.random() * (top + 1));
    tmp = array[current];
    array[current] = array[top];
    array[top] = tmp;
  }
  return array;
}

a = shuffle(a);
Arasto
  • 471
  • 6
  • 25