1

I would like to ask about one tiny riddle. I want to draw lots within in this example 15 figures that should always be different like in the lottery. I have already checked first condition. If for example 1 is equal 1 - please draw lots again, but there is possibility that next sorting will show again number 1. I would like to avoid this some way, to exclude it. There cannot be drawn lots figures the same. Some ideas? :-)

var figureShowed = document.querySelector("div");
var button = document.getElementById("random-figure");
var allFigures = [];

button.addEventListener("click", drawAmount);

function drawAmount() {

    for (i = 0; i <= 5; i++) {
        var random = Math.floor(Math.random() * 15 + 1);

        if (allFigures[0] === allFigures[1, 2, 3, 4, 5]) {
            allFigures[0] = random;
        } else {
            allFigures[i] = random;
        }
    }
    figureShowed.textContent = allFigures.join(" | ");
}
pawel-schmidt
  • 1,125
  • 11
  • 15
Blosom
  • 111
  • 2
  • 12
  • 1
    I think what you are looking for is shuffling algorithm, take a look at this solution: https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array – Pavel Nov 03 '17 at 07:45

2 Answers2

0

Add each random number to an array, alreadyDrawn, and compare subsequent randoms to the numbers in that array. If you have a match, discard and re-random until you don't have a match.

This is probably a naive or non-optimal solution to your problem, but it should work.

Carl
  • 90
  • 1
  • 11
0

You can use includes method to check if random number is already in allFigures array. If it is, then you draw lots again. Check the code:

var figureShowed = document.querySelector("div");
var button = document.getElementById("random-figure");
var allFigures = [];

button.addEventListener("click", drawAmount);

function drawAmount() {
    allFigures = [];
    for (i = 0; i <= 5; i++) {
        let random;
        do {
            random = Math.floor(Math.random() * 15 + 1);
        } while (allFigures.includes(random));
        allFigures.push(random);
    }
    figureShowed.textContent = allFigures.join(" | ");
}
<button id="random-figure">random figure</button>
<div></div>
pawel-schmidt
  • 1,125
  • 11
  • 15
Arkej
  • 2,221
  • 1
  • 14
  • 21