Manipulating odds with JS when using Math.random ()?
When using this function Math.floor((Math.random() * 10) + 1)
i get a random number from 1 to 10. We assume that each number has a 10% chance so we have a 50% chance for odd or even, but what if I wanted to manipulate those chances so that the function is more likely to give me an odd number, for example 70% chance of getting an odd number and 30% chance of getting an even number.
- is it possible to do this?
- What would be the logic applied and how can I do it?
4 answers
The algorithm below consists of two parts:
-
numTipo
is generated: its value will be 0 if the return of a random generation from 1 to 10 is greater than 8, or 1 if negative; and -
numFinal
simply contains a value between 2 and 100 that will always be even , wherenumTipo
is subsequently added.
Adding an odd value to an even value will always generate an odd value. Any other case of addition (even + even, odd + odd) generates a number pair.
This algorithm forces the generation of values whose average distribution is 70% odd and 30% even.
function geraNum() {
var numTipo = Math.floor((Math.random() * 10) + 1) > 7 ? 0 : 1;
var numFinal = Math.floor((Math.random() * 50) + 1) *2 + numTipo;
return numFinal;
}
function geraSerie() {
var contaPar = 0;
var contaImpar = 0;
for (i = 0; i < 1000; i++) {
if (geraNum() % 2 == 0) {
contaPar++;
} else {
contaImpar++;
}
}
console.log("Pares: " + contaPar + ", Ímpares: " + contaImpar);
}
geraSerie();
geraSerie();
geraSerie();
geraSerie();
geraSerie();
The name itself already Says ramdom()
, that is, Returns a random number. If you want to change the chances of the returned number being more even or being more odd, you can create a simple function to check the return of the Code:
let myNumber = Math.floor((Math.random() * 10) + 1);
if (myNumber % 2 == 0) {
// par = faça alguma coisa
} else {
// ímpar = faça alguma coisa
}
However, since it is a random return, only with the if's
you can manipulate the result.
Another Way Is You create your own function (Ex: Math.myRandomFunction()
) and in it you create your logic yourself, storing information and forcing the return to be more even or be more odd.
It would be more interesting for you to say which problem exactly you want to solve. But, according to your example, you can first make a draw to determine whether the number you want is even or odd. Then, home in case, call a function that generates a number only in the pattern you want. For example:
if (x > 7) {
return gerarNumeroPar();
} else {
return gerarNumeroImpar();
}
This function can be done by selecting from a previously generated list or even by drawing successive times until you hit with what you need to generate.
I did not understand very well, but if the goal is to be more conducive to a result, it can be done this way:
if(valor > 7){
// 30% de chance de cair aqui
}else{
// 70% de chance de cair aqui
}