I have a lottery simulator on my website that simulates you playing the lottery every week until your death and tells you how much you would have won or lost. It can take a custom number of balls and rewards scheme, as I made it after Camelot changed the rules for the UK national lottery to give people an idea of how the change could affect their winnings.
Here is the code that actually simulates the lottery, once given values for prizes, number of balls and cost of play:
// Setting up some variables normally given values by POST
$numbers = range(1,49);
$choices = array(8,15,28,36,40,47);
$ZeroWin = 0;
$OneWin = 0;
$TwoWin = 0;
$ThreeWin = 10;
$FourWin = 100;
$FiveWin = 1000;
$BonusWin = 50000;
$Jackpot = 1000000;
$plays = 2000;
$cost = 1;
//No wins yet
$ZeroWinCount = 0; $OneWinCount = 0; $TwoWinCount = 0; $ThreeWinCount = 0;
$FourWinCount = 0; $FiveWinCount = 0;$BonusWinCount = 0;$JackpotCount = 0;
//Lottery simulating
for ($p = 1; $p<=$plays; $p++) {
$hits = 0;
shuffle($numbers); //Spinning the wheel
$BonusHit = False;
$balls = array_slice($numbers, 0, 7); //Choosing balls
for ($a = 0; $a<=5; $a++) {
for ($b = 0; $b<=5; $b++) {
if ($choices["$a"] == $balls["$b"]) {
$hits++; } } }
switch ($hits) {
case 0:
$ZeroWinCount++;
break;
case 1:
$OneWinCount++;
break;
case 2:
$TwoWinCount++;
break;
case 3:
$ThreeWinCount++;
break;
case 4:
$FourWinCount++;
break;
case 5:
for ($q = 0; $q<=5; $q++) {
if ($choices["$q"] == $balls['6']) {
$BonusHit=True;
break;
}
}
if ($BonusHit) {
$BonusWinCount++;
} else {
$FiveWinCount++;
}
break;
case 6:
$JackpotCount++;
}
}
//Calculate winnings
$winnings = (($ZeroWinCount * $ZeroWin) + ($OneWinCount * $OneWin) +
($TwoWinCount * $TwoWin) + ($ThreeWinCount *$ThreeWin) +
($FourWinCount * $FourWin) + ($FiveWinCount * $FiveWin) +
($BonusWinCount * $BonusWin) + ($JackpotCount * $Jackpot));
$losings = $plays * $cost;
$net = $losings - $winnings;
Seven balls are chosen because in the UK we have one bonus ball, and the balls of the player are either chosen by the visitor of the site or through lucky dip.
How efficient is this code? It isn't very complicated, but as the loop can be carried out thousands of times, and has loops within it, small things can make a big difference. If you see an improvement, or an outright mistake, please let me know.
$Numbers
,$choices
,$costs
, and all the$...Win
s. \$\endgroup\$