Random number between 0 and 8, except 5, in Javascript using Math.Random

Asked

Viewed 930 times

2

Hello, using Javascript, I need to generate a random number between the 0 and 8, however the number 5 cannot be one of those numbers generated.

I am returning these numbers so far using the following function:

return(Math.floor(Math.random()*9));

However, the above code only generates any number of 0 to 8.
How do I return a random number other than the 5?
If there is another way to do this without using the Math.Andom function, it will also be useful.

2 answers

5


Quick fix:

var numero = Math.floor(Math.random()*8);
return numero>4 ?  numero+1 : numero

Explanation:

There are many ways to do it, but I’ll make a very simple one for your case.

First, let’s understand the problem. You want one of eight possibilities, but the output is not sequential:

0 1 2 3 4 5 6 7 <-- posição sequencial dos números (aqui é feito o random)
0 1 2 3 4 6 7 8 <-- saída desejada (simplesmente modificamos o retorno com if)

So you want some of these eight numbers. In other words,:

var numero = Math.floor(Math.random()*8);

It’s two sequences, zero to four, and six to eight, so just add one if it’s bigger than four:

return numero>4 ?  numero+1 : numero

If give 0 1 2 3 4 returns 0 1 2 3 4 respectively... ... and, if der 5 6 7 returns 6 7 8 respectively

Thus remaining the code:

var numero = Math.floor(Math.random()*8);
return numero>4 ?  numero+1 : numero

If you do not know the conditional operator (called ternary) is the same as doing this:

var numero = Math.floor(Math.random()*8);
if (numero>4) {
   return numero + 1;
} else {
   return numero;
}

Test here:

function randomDeZeroAOitoMenosOCinco() {
   var numero = Math.floor(Math.random()*8);
   return numero>4 ? numero + 1 :numero;
}

document.getElementById('sortear').onclick = function() {
   document.getElementById('resultado').innerText = randomDeZeroAOitoMenosOCinco();
};
<button id="sortear">Clique-me!</button>
<span id="resultado">?</span>

And if it were a more complex sequence?

Whenever you think of various things (playing cards, non-sequential numbers, names) think of them as "items" and not sequentially (even if they are numbers, you can "number each one in sequence"). Then you draw his index, and then you take the value:

var possibilidades = [ 0, 1, 2, 3, 4, 6, 7, 8 ];
return possibilidades[Math.random()*possibilidades.length];

Noticed that in this case you can put on array the sequence you want?

Test here:

function randomCustomizado() {
   var possibilidades = [ 0, 1, 2, 3, 4, 6, 7, 8 ];
   return possibilidades[Math.floor(Math.random()*possibilidades.length)];
}

document.getElementById('sortear').onclick = function() {
   document.getElementById('resultado').innerText = randomCustomizado();
};
<button id="sortear">Clique-me!</button>
<span id="resultado">?</span>

  • Excellent. In my case of the question, this part of the code is inside a switch case, because I’m creating a memory game to learn Javascript (I’m a beginner). With just a few modifications of your solution placing within a recursive function, it worked here.

  • @Igorpedra added a more interesting function at the end, which serves for any sequence (and even for strings).;

  • 1

    If you remember this, it will help a lot when you need "Random" of various items: Do not add the items (in your case it would be like taking the values you want and number from zero to eight, and the fifth value is six, and so on), it facilitates the reasoning.

4

In this role will never give five:

function numberRandom() {
    let num = 5
    while (num === 5) {
        num = Math.floor(Math.random() * 8)
    }
    return num
}
  • 2

    This way in fact will never give five, but note that the draw itself is not deterministic (the loop may have to run several times in a row until draw a number that is not five) - For the purpose of a quick test works, but to generate a large amount of numbers will end up having more than 11% rework on average (chance to give 5 and have to draw again)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.