Tengo un enfoque ligeramente diferente a algunas de las respuestas aquí. Creé un porcentaje flexible basado en la cantidad de elementos que desea sumar, y luego más o menos 10% de forma aleatoria.
Entonces hago esto n-1 veces (n es el total de iteraciones), por lo que tiene un resto. El resto es el último número, que no es en sí mismo aleatorio, pero está basado en otros números aleatorios.
Funciona bastante bien.
/**
* Calculate n random numbers that sum y.
* Function calculates a percentage based on the number
* required, gives a random number around that number, then
* deducts the rest from the total for the final number.
* Final number cannot be truely random, as it's a fixed total,
* but it will appear random, as it's based on other random
* values.
*
* @author Mike Griffiths
* @return Array
*/
private function _random_numbers_sum($num_numbers=3, $total=500)
{
$numbers = [];
$loose_pcc = $total/$num_numbers;
for($i = 1; $i < $num_numbers; $i++) {
// Random number +/- 10%
$ten_pcc = $loose_pcc * 0.1;
$rand_num = mt_rand(($loose_pcc - $ten_pcc), ($loose_pcc + $ten_pcc));
$numbers[] = $rand_num;
}
// $numbers now contains 1 less number than it should do, sum
// all the numbers and use the difference as final number.
$numbers_total = array_sum($numbers);
$numbers[] = $total - $numbers_total;
return $numbers;
}
Este:
$random = $this->_random_numbers_sum();
echo 'Total: '. array_sum($random) ."\n";
print_r($random);
Salidas:
Total: 500
Array
(
[0] => 167
[1] => 164
[2] => 169
)
esto es posible. ¿Has hecho algún intento? –
¿Con qué parte de esto estás teniendo problemas? ¿Sabes cómo generar números aleatorios? –
¿Esto no parece un problema con PHP? – benck