Skip to content

Instantly share code, notes, and snippets.

@zacblazic
Created March 20, 2011 18:48
Show Gist options
  • Save zacblazic/878546 to your computer and use it in GitHub Desktop.
Save zacblazic/878546 to your computer and use it in GitHub Desktop.
Finds the maximum, minumum and average rolls to complete a snakes and ladders game
/*
* Author: Zac Blazic (210208880)
* Date: 19/03/2011
* File: SnakesAndLadders.cpp
* Description: Finds the maximum, minumum and average rolls to complete a snakes and ladders game.
*/
#include <iostream>
#include <ctime>
#define LAST_SQUARE 100
#define MAX_ROLL 6
#define NUM_SNAKES 10
#define NUM_LADDERS 9
#define NUM_GAMES 1000000
enum
{
SOURCE,
DESTINATION
};
int playGame(int snakes[][2], int ladders[][2]);
void simulateGames(int &min, int &max, float &average, int snakes [][2], int ladders[][2]);
int main()
{
int snakes[NUM_SNAKES][2] = {16, 6, 47, 26, 49, 11, 56, 53, 62, 19, 64, 60, 87, 24, 93, 73, 95, 75, 98, 78};
int ladders[NUM_LADDERS][2] = {1, 38, 4, 14, 9, 31, 21, 42, 28, 84, 36, 44, 51, 67, 71, 91, 80, 100};
int min;
int max;
float average;
int initialRoll;
initialRoll = playGame(snakes, ladders);
min = initialRoll;
max = initialRoll;
simulateGames(min, max, average, snakes, ladders);
std::cout << "Minimum rolls: " << min << std::endl
<< "Maximum rolls: " << max << std::endl
<< "Average rolls: " << average << std::endl;
return 0;
}
int playGame(int snakes[][2], int ladders[][2])
{
int tokenSquare = 0;
int totalRolls = 0;
int roll;
while(tokenSquare != LAST_SQUARE)
{
do
{
roll = (rand() % MAX_ROLL) + 1;
totalRolls++;
}
while(tokenSquare + roll > LAST_SQUARE);
tokenSquare += roll;
for(int i = 0; i < NUM_SNAKES; i++)
{
if(tokenSquare == snakes[i][SOURCE])
{
tokenSquare = snakes[i][DESTINATION];
}
}
for(int i = 0; i < NUM_LADDERS; i++)
{
if(tokenSquare == ladders[i][SOURCE])
{
tokenSquare = ladders[i][DESTINATION];
}
}
}
return totalRolls;
}
void simulateGames(int &min, int &max, float &average, int snakes[][2], int ladders[][2])
{
int gameRolls;
int totalRolls = 0;
int gamesPlayed = 0;
srand(unsigned(time(0)));
for(int i = 0; i < NUM_GAMES; i++)
{
gameRolls = playGame(snakes, ladders);
if(gameRolls > max)
{
max = gameRolls;
}
else if(gameRolls < min)
{
min = gameRolls;
}
totalRolls += gameRolls;
gamesPlayed++;
}
average = totalRolls / float(gamesPlayed);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment