How to generate random numbers in javascript, differently

4

Hello, I need your help!

I need to generate random javascript , so that they are only generated 5 out of 5 and within a limitation, for example 5-555. Example: 5, 355, 425, 125, 550

  • Multiple numbers of 5 (5,10,15,20,25,30,35,40 ...)
  • Numbers must be at least 5 and at most 555!
asked by anonymous 02.05.2018 / 03:59

3 answers

1

Simply put:

Math.round(Math.random() * 550 / 5) * 5 + 5;

If you want something with variable values or that can be easily called, you can create a function:

function myRandom(min, max, multiple) {
    return Math.round(Math.random() * (max - min) / multiple) * multiple + min;
}
    
02.05.2018 / 04:32
2

Simply generate a number from 1 to 111 and then multiply by 5, so you have a result between 1 * 5 and 111 * 5. I think this is the easiest and clearest solution to understand, maybe even faster.

An easy, relatively safe way to do this would be to grab the 7 least significant bits of a byte and discard them if it is greater than 111 or less than 1.

function NumeroAleatorio() {
  while (true) {
    // Obtemos o numero aleátorio entre 0 até 255
    var numero = new Uint8Array(1);
    window.crypto.getRandomValues(numero);

    // Obtemos apenas os 7 primeiros bits, fazendo ser de 0 até 127.
    numero = numero[0] & 0x7F;

    // Se for válido, retornamos ele multiplicado por 5.
    if (numero >= 1 && numero <= 111) {
      return numero * 5;
    }
  }
}

document.write("Gerado: " + NumeroAleatorio())

This uses window.crypto.getRandomValues which is safer, but slower than Math.Random . In the comments mentioned it would be for a game, depending on the case Math.Random is better, for being faster.

There is a 14% chance, if my accounts are right, of the value being out of the desired (from 1 to 111), if the user is very unlucky the page can stay in an infinite loop if all the attempts are within the 14%.

    
02.05.2018 / 23:18
0

Try something like this:

function obterNumeroAleatorio(n1, n2) {
  const min = Math.ceil(n1);
  const max = Math.floor(n2);
  return Math.floor(Math.random() * (max - min)) + min;
}

function modificarNumeroParaSerMultiploDeCinco(n) {
  const numeroDivisivelPorCinco = Math.round(n / 5) * 5;
  return numeroDivisivelPorCinco;
}

const numeroAleatorio = obterNumeroAleatorio(5, 555);
const numeroFinal = modificarNumeroParaSerMultiploDeCinco(numeroAleatorio);

console.log('numeroAleatorio:', numeroAleatorio);
console.log('numeroFinal:', numeroFinal);

In the first constant, the number is generated randomly, and in the second it is made a multiple of 5. What you need is probably just numeroFinal .

    
02.05.2018 / 04:19