Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function rollDice(){
- $roll = random_int(1,6);
- //echo("Rolled: " . $roll . "\n");
- return $roll;
- }
- function runGame(){
- $snakes = array(
- 14 => 4,
- 17 => 7,
- 31 => 9,
- 38 => 20,
- 54 => 34,
- 59 => 40,
- 62 => 19,
- 64 => 60,
- 67 => 51,
- 81 => 63,
- 84 => 28,
- 91 => 71,
- 93 => 73,
- 95 => 75,
- 99 => 78
- );
- $moves = 0;
- $fallen = 0;
- $pos = 0;
- for($pos = 0; $pos < 100; $pos += 0){
- //Roll 6 to start
- if($pos == 0){
- if($moves == 0){
- if(rollDice() != 6 && rollDice() != 6 && rollDice() != 6){
- $moves ++;
- continue;
- }
- }else{
- if(rollDice() != 6){
- $moves ++;
- continue;
- }
- }
- }
- $roll = rollDice();
- $pos += $roll;
- //Hit 100 exactly, go back when overshooting
- if($pos > 100){
- //echo "From $pos to " . 100 - ($pos - 100);
- $pos = 100 - ($pos-100);
- }
- $moves ++;
- //Fall down the snake ladder
- if( array_key_exists($pos, $snakes) ){
- $moveTo = $snakes[$pos];
- //echo "Oh no! Falling from $pos to $moveTo!\n";
- $pos = $moveTo;
- $fallen++;
- }
- if($roll == 6){
- $moves --;
- continue;
- }
- }
- //echo "YOU WON! Turns: $moves and fallen $fallen times.";
- return [$moves, $fallen];
- }
- $sampleSize = 100000;
- $totalMoves = [];
- $totalFalls = [];
- for($i = 0;$i < $sampleSize;$i ++){
- $game = runGame();
- $totalMoves[] = $game[0];
- $totalFalls[] = $game[1];
- }
- $averageMoves = array_sum($totalMoves) / $sampleSize;
- $averageFalls = array_sum($totalFalls) / $sampleSize;
- $maxMoves = max($totalMoves);
- $maxFalls = max($totalFalls);
- $minMoves = min($totalMoves);
- $minFalls = min($totalFalls);
- echo "Average turns: $averageMoves \n";
- echo "Average falls: $averageFalls \n";
- echo "Game with most turns: $maxMoves \n";
- echo "Game with most falls: $maxFalls \n";
- echo "Game with least turns: $minMoves \n";
- echo "Game with least falls: $minFalls \n";
Advertisement
Add Comment
Please, Sign In to add comment