mercredi 25 septembre 2019

Discrepancy between 2 functions [PHP]

I have 2 functions, in first I'am generation random number and setting probability. In second functions cheking the generated number is in certain range. And if its in certain range setting value to variable.

            function chance($input = array()) {
                $number  = rand(0, array_sum($input) * 10);
                $starter = 0;
                $b       = 3;
                foreach ($input as $key => $val) {
                    $starter += $val * 10;
                    if ($number <= $starter) {
                        $ret = $key;
                        break;
                    }

                }
                return $ret;
                //return $b;;
            }

            function in_range($number, $min, $max, $inclusive = FALSE) {
                if (is_int($number) && is_int($min) && is_int($max)) {
                    return $inclusive ? ($number >= $min && $number <= $max) : ($number > $min && $number < $max);
                }

                return FALSE;
            }

            $array = array(
                rand(0, 9885) => 81.9,
                rand(9886, 9985) => 15.1,
                rand(9986, 9993) => 1,
                rand(9994, 9997) => 0.09,
                rand(9998, 9999) => 0
            );
    $rolledNumber = chance($array);
                $coinsWon = 0;
if (in_range($rolledNumber, 0, 9885) == true) {
        $coinsWon = 5;
                } elseif (in_range($rolledNumber, 9886, 9985) == true) {
                    $coinsWon = 10;
                } elseif (in_range($rolledNumber, 9986, 9993) == true) {
                    $coinsWon = 50;
                }

After a few tests found that there are dismaches. For example:

Getting number 9884, and the value of coinswon is 10, but should be 5. Also I thing that the probability options its not working properly, because for 9986, 9993 numbers I've set 1% probability, but numbers in this range are generated frequently




Aucun commentaire:

Enregistrer un commentaire