Coger un valor aleatorio dentro de un array
Funciones para elegir de forma aleatoria un valor de entre los valores de un array.
Javascript
/**
* Get random array value. Accept as values array, string, number, float, boolean, object and null.
*
* @param {array} values - The array to get random value.
* @returns {any} The random value from array.
*/
function getRandom(values){
return values[Math.floor(Math.random() * values.length)];
}
Ejemplo:
let data = [1, 2, "3", 4, 5, "arr", [1, 2, 3], null, false, 10.5];
console.log(getRandom(data));
PHP
/**
* Get random array value. Accept as values array, string, number, float, boolean, object and null.
*
* @param {array} values - The array to get random value.
* @returns {any} The random value from array.
*/
function getRandom($values){
return $values[round(mt_rand(0, count($values)) )];
}
Ejemplo:
$data = [1, 2, "3", 4, 5, "arr", [1, 2, 3], null, false, 10.5];
$random = getRandom($data);
var_dump($random);
Python
Para generar números aleatorios en Python deberemos utilizar el módulo random de la biblioteca estándar.
Este módulo provee varias funciones para poder generar números aleatorios de distintas formas y con distintos parámetros.
Utilizando la función choice():
from random import choice
data = [1, 2, "3", 4, 5, "arr", [1, 2, 3], 10.5]
print(choice(data))