Create 3 random int params with sum of 100

Issue

I need to create a player with 3 properties:

  • Life (must be a random integer from 1 to 100);
  • Attack (must be a random integer from 1 to 100);
  • Defense (must be a random integer from 1 to 100);
    But the total sum of all properties must be 200 (Life + Attack + Defense = 200). No more or less.
    I’ve tried to make something like this:
public function initPlayer(){
        $life = random_int(1, 100);
        $attack = random_int(1, 100);
        $lifeAttack = $life + $attack;
        if($lifeAttack >= 100) {
            $defense = 200 - $lifeAttack;
        } else {
            $defense = random_int(1, 100);
        }
        echo $life . '-' . $attack . '-' . $defense;
    }

But it works correctly only if the sum of two params is equal or more than 100.

Solution

If the three values of life + attack + defense are to be real random numbers in the range 1..100, then the total is only 200 with a very low probability.
When the third value is calculated, it is no longer random.

The correct solution is: The 3 values have to be determined again and again until the total is equal 200.

for($sum = 0;$sum !== 200;){
   $life = random_int(1, 100);
   $attack = random_int(1, 100);  
   $defense = random_int(1, 100);
   $sum = $life + $attack + $defense;
}

var_dump($life,$attack,$defense,$life + $attack + $defense);

Output example:

int(65) int(77) int(58) int(200)

Answered By – jspit

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published