Advertisement
ssoni

princessSim.c

Mar 7th, 2022
1,039
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.06 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <cs50.h>
  3. #include <time.h>
  4. #include <stdlib.h>
  5. #include <unistd.h>
  6.  
  7. int getPrincessMove(int loc);
  8. void printBoard(int hisLoc, int herLoc);
  9. int doRound(int verbose);
  10.  
  11. int main(int argc, string argv[])
  12. {
  13.     srand(time(0));
  14.     int days=0;
  15.     int maxDays=0;
  16.  
  17.     int numRounds = atoi(argv[1]);
  18.  
  19.     for (int i=0; i<numRounds; i++)
  20.     {
  21.         days = doRound(0);
  22.         if (days > maxDays)
  23.         {
  24.             maxDays = days;
  25.         }
  26.     }
  27.     printf("The worst case took %i days.\n", maxDays);
  28. }
  29.  
  30. int getPrincessMove(int loc)
  31. {
  32.         int pmove=0;
  33.  
  34.         if (loc == 17)
  35.         {
  36.             pmove = -1;
  37.         }
  38.         else if (loc == 1)
  39.         {
  40.             pmove = 1;
  41.         }
  42.         else
  43.         {
  44.             pmove = rand() % 2;
  45.             if (pmove == 0)
  46.             {
  47.                 pmove = -1;
  48.             }
  49.         }
  50.         return pmove;
  51. }
  52.  
  53. void printBoard(int hisLoc, int herLoc)
  54. {
  55.     for (int i=1; i<=17; i++)
  56.     {
  57.         if (i==hisLoc)
  58.         {
  59.             printf("X");
  60.         }
  61.         else if (i == herLoc)
  62.         {
  63.             printf("*");
  64.         }
  65.         else
  66.         {
  67.             printf("_");
  68.         }
  69.     }
  70.     printf("\n");
  71. }
  72.  
  73. int doRound(int verbose)
  74. {
  75.     int ppos;
  76.     int numGuesses=0;
  77.     int princeDirection=1;
  78.     int guess=1;
  79.  
  80.     //initial princess location
  81.     ppos = (rand() % 17) + 1;  //0-16 +1shift to 1-17
  82.  
  83.     while ( ppos != guess)
  84.     {
  85.         //move princess
  86.         ppos = ppos + getPrincessMove(ppos);
  87.  
  88.         //make guess
  89.         if (numGuesses == 15)
  90.         {
  91.             princeDirection = 0;
  92.         }
  93.         else if (numGuesses == 16)
  94.         {
  95.             princeDirection = -1;
  96.         }
  97.         guess = guess + princeDirection;
  98.  
  99.         //update total days
  100.         numGuesses++;
  101.  
  102.         //display board
  103.         if (verbose == 1)
  104.         {
  105.             printBoard(guess, ppos);
  106.             //sleep(1);
  107.         }
  108.     }
  109.     printf("You got her in %i days.\n", numGuesses);
  110.     return numGuesses;
  111. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement