Divide a single number into a set of unique random numbers in PHP
php
Solution
You can try using a small function to generate these numbers:
function generateRandomNumbers($max, $count)
{
$numbers = [];
for ($i = 1; $i < $count; $i++) {
$random = mt_rand(0, $max / ($count - $i));
$numbers[] = $random;
$max -= $random;
}
$numbers[] = $max;
shuffle($numbers);
return $numbers;
}
echo '<pre>';
print_r(generateRandomNumbers(100, 10));
echo '</pre>';
The function will generate an array like:
Array
(
[0] => 0
[1] => 1
[2] => 6
[3] => 11
[4] => 14
[5] => 13
[6] => 3
[7] => 6
[8] => 13
[9] => 33
)
Please note that instead of `$random = mt_rand(0, $max / ($count - $i));` I could use directly `$random = mt_rand(0, $max)` but in the later case the chances to get a lot of 0 in the resulted array are bigger than the first case.
Problem
I want to start with a predetermined single number, but then have multiple random numbers that when added up, their total is the number I started with. For example, I have 100, but want to have 10 random numbers that when they are added together, make up 100. With my limited knowledge, I wrote this: ``` <?php $_GET['total'] = $total; $_GET['divided'] = $divided; echo 'Starting with total: ' . $total; echo '<br />'; echo 'Divided between: ' . $divided; $randone = rand(1, $total); $randonecon = $total - $randone; echo '<br />'; echo 'First random number: ' . $randone; $randtwo = rand(1, $randonecon); $randtwocon = $total - $randtwo; echo '<br />'; echo 'Second random number: ' . $randtwo; ?> ``` Of course, it's a failure, because I don't know how to make the numbers be in an array that doesn't let them exceed the given total. Thanks entirely to Matei Mihai, it's done! ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Randomize</title> </head> <body> <?php $_GET['total'] = $total; $_GET['divided'] = $divided; function generateRandomNumbers($max, $count) { $numbers = array(); for ($i = 1; $i < $count; $i++) { $random = mt_rand(0, $max / ($count - $i)); $numbers[] = $random; $max -= $random; } $numbers[] = $max; return $numbers; } echo '<pre>'; print_r(generateRandomNumbers($total, $divided)); echo '</pre>'; ?> <form id="form1" name="form1" method="get" action=""> <label for="total">Total</label> <br /> <input type="text" name="total" id="total" /> <br /> <label for="divided">Divided</label> <br /> <input type="text" name="divided" id="divided" /> <br /> <input type="submit" value="Go!"> </form> </body> </html> ```