samedi 28 juillet 2018

PHP Split int into random values

I have a int called v_cnt which im using a maximum value for a voting system, them im using mt_rand to generate a random number of 'votes' (used for gaming purposes not a rigged system)

// vote 1
$vote_limit = $v_cnt;
$vote_1 = mt_rand(0, $vote_limit); 
// vote 2
$vote_limit = $v_cnt - $vote_1; if($vote_limit < 0){ $vote_limit = 0;}
$vote_2 = mt_rand(0, $vote_limit);
// vote 3
$vote_limit = $v_cnt - ($vote_1 + $vote_2); if($vote_limit < 0){ $vote_limit = 0;}
$vote_3 = mt_rand(0, $vote_limit);

This gives me vote_1, vote_2 and vote_3 which is ideal. But, since mt_rand is a random value up to the limit, im not getting quite the result i need as i need it to calculate like this;

(vote_1 + vote_2 + vote_3) = $v_cnt

So essentially i need to split an int into 3 random values which must add up to equal the starting number. I hope this makes sense.

Thank you.




Aucun commentaire:

Enregistrer un commentaire