0

Can a random number being generated and split/divided into let say 3 individual numbers randomly in PHP? (so they add up to the random number)

Basically I have a random number (range from 0 to 15)

For example:

There are 14 available now
- 2 in Gotham City
- 8 in Lakeview Hills
- 4 in Eskimoville

(just a dummy to give you the idea)

Isn´t there a simple approach to accomplish this?

Have a nice weekend!

  • It´s very similar but there is a fixed number of 100. Would work perhaps if 100 was a max random range - and the array in that case sometimes echos randomly amount of numbers but should be fixed – Ingþór Ingólfsson Oct 31 '14 at 11:15
  • @IngþórIngólfsson The same logic in the duplicate question applies. The only thing different is that the maximum random range is random number here, which is fine since you'll know that number once you generate it. – Alternatex Oct 31 '14 at 11:18

1 Answers1

0

basic implementation would need error checking + not 100% random

<?php
//first initial number
// range must be 3-15 to get 3 random additions
$i = rand(3,15);
echo $i;
// generate what 3 number adds to $i
$one = rand(1,$i-2);
$i-=$one;
$two = rand(1,$i-1);
$i -= $two;
$three = rand(1,$i);
$i -= $three;
if($i > 0){
// add remained to third number
$three += $i;
}

echo $one;
echo $two;
echo $three;

?>
user4185589
  • 117
  • 3
  • This is exactly the solution. And I could have rand(0,15) because I need the zero value too if nothing is available - This scripts seems to be flawless. - I think people are way to quick to judge a question as possible duplicate – Ingþór Ingólfsson Oct 31 '14 at 11:48