VERSIÓN EN ESPAÑOL

Source
Saludo amigos Geek quiero en mi camino de aprendizaje de la programación, en el cual vamos a nuestro ritmo y disfrutando el proceso, compartirles algunas funcionalidades que me parecen interesantes explicar su sentido, esto es, comprender su lógica interna y, sobre todo, por qué son útiles.
Math.random()
Voy a empezar con la función de aleatoriedad, la cual nos permite generar un número aleatorio entre el rango que nosotros definamos. He aquí donde está lo interesante, pues, conseguir un número en JavaScript es relativamente sencillo, pues nos basta usar la función nativa del objeto Math, la cual es:
Math.random()
Ahora bien, los números que esta función nos da como opciones están comprendidos entre el 0 (no incluido) y el 1 (no incluido), lo cual no es práctico porque una función así nos dará resultados tales como: 0.190,0.013, 0.518, etc. Por lo que debemos, encontrar la forma de obtener números enteros y luego la manera de eliminar los decimales.
Lo primero, lo podemos resolver multiplicando la función anterior por el número que queramos esté comprendido el rango de número aleatorio (3,7,15,100, etc.). Lo segundo es más fácil todavía, pues, solo basta que elijamos entre dos funciones nativas:
Math.round()
Esta función nos redondea el entero a su número más cercano:
Math.round(Math.random()*47)
Tengamos en cuenta aquí que seguimos las leyes básicas de las matemáticas, resolvemos la operativa interna del paréntesis primero para luego hacer lo demás. Es decir, esta función la pudiésemos desglosar así:
let num = Math.random()*47
let numRound = Math.round(num)
console.log({num,numRound})
- let num, variable que me guarda un número aleatorio entre 0 (no incluido) y 47 (no incluido)
- let numRound, variable que me redondea el número anterior al número más cercano. Una vez más, aquí volvemos a aplicar las matemáticas, pues, a partir del decimal .50 el redondeo es al número más próximo superior.
- Finalmente, los resultados lo mostramos en la consola.
Así pues, una primera función aleatoria que podemos armar con lo visto aquí es:
function redondeoAleatorio (rango) {
let numRound = Math.round(Math.random()*rango)
return numRound
}
// The same Function but by steps
⬇️ ⬇️ ⬇️ ⬇️
function redondeoAleatorio (rango) {
let num = Math.random()*rango
let numRound = Math.round(num)
return numRound
}
- Donde el parámetro rango espera como argumento el rango de números aleatorios que buscamos, por ejemplo:
redondeoAleatorio(47)
redondeoAleatorio(6)
redondeoAleatorio(205)
Math.floor()
Técnicamente, este método nativo redondea el número hacia abajo (puesto que existe otro - Math.ceil()) que redondea hacia arriba, pero para entendernos digamos que este método quita los decimales a cualquier entero.
Math.floor(Math.random()*47)
Me parece que desglosando esta función podemos entender su diferencia con Math.round(), específicamente fijándonos en la salida que nos da la consola.
let num = Math.random()*47
let numInt = Math.floor(num)
console.log({num,numInt})
- En la consola, vamos a poder apreciar que cualquiera sean los decimales que acompañen a los números aleatorios, estos siempre serán eliminados, quedándonos solo el número entero.
La segunda función que podemos realizar es haciendo ligeros cambios en la anterior la siguiente:
function aleatorioEntero (rango) {
let numInt = Math.floor(Math.random()*rango)
return numInt
}
/ The same Function but by steps
⬇️ ⬇️ ⬇️ ⬇️
function aleatorioEntero(rango) {
let num = Math.random()*rango
let numInt = Math.floor(num)
return numInt
}
- Cambiamos el nombre de la función a lo que ella nos devuelve, un entero sin importar los decimales que haya.
- Por eso, usamos el método Math.floor() y le dimos a la variable guardada y retornada el nombre de numInt.
Bonus: Partir de uno y tomar el último número del rango
En la última función planteada tenemos el problema de que nunca nos saldrá el número del rango, ya que por ejemplo si estamos buscando aleatorioEntero(47) el número máximo será 46,9, pero como floor nos quita los decimales, en realidad, nunca tendremos el número 47, la solución es sumar un uno a la ecuación, con lo cual además partiremos a buscar un rango partiendo del número 1, lo cual es mucho más práctico. Por ello, esta función la podemos mejorar de la siguiente manera:
function aleatorioEntero (rango) {
let numInt = Math.floor(Math.random()*rango) + 1
return numInt
}

ENGLISH VERSION
Programming - JS: Randomness function

Source
Greetings Geek friends I want to share with you some functionalities that I find interesting to explain their meaning, that is, to understand their internal logic and, above all, why they are useful.
Math.random()
I am going to begin with the random function, which allows us to generate a random number between the range that we define. Here is where it is interesting, because, to get a number in JavaScript is relatively simple, because we only need to use the native function of the Math object, which is:
Math.random()
Now, the numbers that this function gives us as options are between 0 (not included) and 1 (not included), which is not practical because a function like this will give us results such as: 0.190,0.013, 0.518, etc. So we must find a way to obtain integers and then find a way to eliminate the decimals.
The first, we can solve it by multiplying the previous function by the number that we want to be included in the range of random number (3,7,15,100, etc.). The second is even easier, because we only need to choose between two native functions:
Math.round()
This function rounds the integer to its nearest number:
Math.round(Math.random()*47)
Let's keep in mind here that we follow the basic laws of mathematics, we solve the internal operation of the parenthesis first and then do the rest. That is, this function could be broken down as follows:
let num = Math.random()*47
let numRound = Math.round(num)
console.log({num,numRound})
- let num, variable that stores a random number between 0 (not included) and 47 (not included) - let numRound, variable that rounds the previous number to the nearest number. Once again, here we apply again the mathematics, because, from the decimal .50 the rounding is to the nearest higher number - Finally, we show the results in the console.
So, a first random function that we can put together with what we have seen here is:
function redondeoAleatorio (rango) {
let numRound = Math.round(Math.random()*rango)
return numRound
}
// The same Function but by steps
⬇️ ⬇️ ⬇️ ⬇️
function redondeoAleatorio (rango) {
let num = Math.random()*rango
let numRound = Math.round(num)
return numRound
}
- Where the parameter rango expects as argument the range of random numbers we are looking for, for example:
redondeoAleatorio(47)
redondeoAleatorio(6)
redondeoAleatorio(205)
Math.floor()
Technically, this native method rounds the number down (since there is another one - Math.ceil()) that rounds up, but for the sake of understanding let's say that this method removes the decimal places from any integer.
Math.floor(Math.random()*47)
It seems to me that by breaking down this function we can understand its difference with Math.round(), specifically by looking at the output that the console gives us.
let num = Math.random()*47
let numInt = Math.floor(num)
console.log({num,numInt})
- In the console, we will be able to appreciate that whatever the decimals that accompany the random numbers, these will always be eliminated, leaving only the whole number.
The second function that we can perform is by making slight changes in the previous one, the following:
function aleatorioEntero (rango) {
let numInt = Math.floor(Math.random()*rango)
return numInt
}
/ The same Function but by steps
⬇️ ⬇️ ⬇️ ⬇️
function aleatorioEntero(rango) {
let num = Math.random()*rango
let numInt = Math.floor(num)
return numInt
}
- We changed the name of the function to what it returns, an integer regardless of decimals - so we used the Math.floor() method and gave the saved and returned variable the name numInt.
Bonus: Start from one and take the last number of the range.
In the last function we have the problem that we will never get the number of the range, because for example if we are looking for randomEnter(47) the maximum number will be 46.9, but as floor removes the decimals, in reality, we will never have the number 47, the solution is to add a one to the equation, with which we will also start looking for a range starting from the number 1, which is much more practical. Therefore, we can improve this function in the following way:
function aleatorioEntero (rango) {
let numInt = Math.floor(Math.random()*rango) + 1
return numInt
}


