Skip to content
Advertisement

Developing a Reward Box Algorithm [closed]

I’m trying to build a probability algorithm that will give the user his/her reward based on these probabilities.

1 $ – 60%

2 $ – 25%

5 $ – 12%

10 $ – 1.99%

50 $ – 1%

500 $ – 0.01%

How can I do that? Can you give me any examples of code? Any help is appreciated!

Advertisement

Answer

You can make use of the rand function here. Multiply all the probabilities by 100 to be able to work with the integral types, with their total sum being 10000. Generate a random number between 1 and 10000. Now, for the chances to be 60%, if the random number is between, say, 1 and 6000, the reward would be 1$, and so on for other probabilities.

<?php

function reward() {

    $random = rand(1, 10000);

    if($random >= 1 && $random <= 6000) {
        $reward = 1;
    } else if($random > 6000 && $random <= 8500) {
        $reward = 2;
    } else if($random > 8500 && $random <= 9700) {
        $reward = 5;
    } else if($random > 9700 && $random <= 9899) {
        $reward = 10;
    } else if($random > 9899 && $random <= 9999) {
        $reward = 50;
    } else {
        $reward = 500;
    }

    return $reward;
}

echo reward();

?>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement