Advertisement
John_Conner

Shortened Multidimensional Array App

Mar 11th, 2014
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.88 KB | None | 0 0
  1. // Chapter 8 Programming Project #9
  2.  
  3. #include <stdio.h>
  4. #include <stdbool.h>
  5. #include <stdlib.h>
  6. #include <time.h>
  7.  
  8. #define SIZE 10
  9. #define PATH_SIZE 25
  10. #define ROW_SIZE ((int) (sizeof(board) / sizeof(board[0])))
  11.  
  12. int main(void)
  13. {
  14.     char board[SIZE][SIZE] = {};
  15.     // 0 = Up, 1 = Down, 2 = Left, 3 = Right
  16.     unsigned short i = 0, x, y;
  17.     // Generate a random number
  18.     srand((unsigned) time(NULL));
  19.     int dir = rand() % 4;
  20.     // Set all positions of board to '.'
  21.     for (x = 0; x < ROW_SIZE; x++) {
  22.         for (y = 0; y < ROW_SIZE; y++)
  23.             board[x][y] = '.';
  24.     }
  25.     x = 0;
  26.     y = 0;
  27.     board[0][0] = 'A';
  28.     // Generate the path
  29.     while (i != PATH_SIZE) {
  30.         for (i = 0; i < PATH_SIZE;) {
  31.             // Check the direction and replace that char
  32.             switch (dir) {
  33.                 case 0: if ((y - 1) >= 0 &&
  34.                             board[x][y - 1] == '.') {
  35.                     board[x][--y] = i + 'B';
  36.                     ++i;
  37.                 } break;
  38.                 case 1: if ((y + 1) >= 0 &&
  39.                             board[x][y + 1] == '.') {
  40.                     board[x][++y] = i + 'B';
  41.                     ++i;
  42.                 } break;
  43.                 case 2: if ((x - 1) >= 0 &&
  44.                             board[x - 1][y] == '.') {
  45.                     board[--x][y] = i + 'B';
  46.                     ++i;
  47.                 } break;
  48.                 case 3: if ((x + 1) >= 0 &&
  49.                             board[x + 1][y] == '.') {
  50.                     board[++x][y] = i + 'B';
  51.                     ++i;
  52.                 } break;
  53.             }
  54.         // Reset the random direction
  55.         dir = rand() % 4;
  56.         }
  57.     }
  58.     // Print the board
  59.     for (x = 0; x < ROW_SIZE; x++) {
  60.         for (y = 0; y < ROW_SIZE; y++)
  61.             printf("%c ", board[x][y]);
  62.         printf("\n");
  63.     }
  64.  
  65.     return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement