Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <cs50.h>
- #include <time.h>
- #include <stdlib.h>
- #include <unistd.h>
- int getPrincessMove(int loc);
- void printBoard(int hisLoc, int herLoc);
- int doRound(int verbose);
- int main(int argc, string argv[])
- {
- srand(time(0));
- int days=0;
- int maxDays=0;
- int numRounds = atoi(argv[1]);
- for (int i=0; i<numRounds; i++)
- {
- days = doRound(0);
- if (days > maxDays)
- {
- maxDays = days;
- }
- }
- printf("The worst case took %i days.\n", maxDays);
- }
- int getPrincessMove(int loc)
- {
- int pmove=0;
- if (loc == 17)
- {
- pmove = -1;
- }
- else if (loc == 1)
- {
- pmove = 1;
- }
- else
- {
- pmove = rand() % 2;
- if (pmove == 0)
- {
- pmove = -1;
- }
- }
- return pmove;
- }
- void printBoard(int hisLoc, int herLoc)
- {
- for (int i=1; i<=17; i++)
- {
- if (i==hisLoc)
- {
- printf("X");
- }
- else if (i == herLoc)
- {
- printf("*");
- }
- else
- {
- printf("_");
- }
- }
- printf("\n");
- }
- int doRound(int verbose)
- {
- int ppos;
- int numGuesses=0;
- int princeDirection=1;
- int guess=1;
- //initial princess location
- ppos = (rand() % 17) + 1; //0-16 +1shift to 1-17
- while ( ppos != guess)
- {
- //move princess
- ppos = ppos + getPrincessMove(ppos);
- //make guess
- if (numGuesses == 15)
- {
- princeDirection = 0;
- }
- else if (numGuesses == 16)
- {
- princeDirection = -1;
- }
- guess = guess + princeDirection;
- //update total days
- numGuesses++;
- //display board
- if (verbose == 1)
- {
- printBoard(guess, ppos);
- //sleep(1);
- }
- }
- printf("You got her in %i days.\n", numGuesses);
- return numGuesses;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement