toth_rand.c (1170B)
1 /* Exercise 6.25 (a) */ 2 3 #include <stdio.h> 4 #include <stdlib.h> 5 #include <time.h> 6 7 #define BSIZE 8 /* board size */ 8 9 int main(void) 10 { 11 int board[BSIZE][BSIZE] = { { 0 } }; 12 /* 0 1 2 3 4 5 6 7 */ 13 int horizontal[BSIZE] = { 2, 1, -1, -2, -2, -1, 1, 2 }; 14 int vertical[BSIZE] = { -1, -2, -2, -1, 1, 2, 2, 1 }; 15 16 int moveNumber, i, r, c; 17 int currentRow = 0, currentColumn = 0; 18 board[currentRow][currentColumn] = -1; /* current position */ 19 20 srand( time(NULL) ); 21 22 for(i = 1; i <= BSIZE*BSIZE; i++) { 23 moveNumber = rand() % 8; 24 25 r = currentRow + vertical[moveNumber]; 26 c = currentColumn + horizontal[moveNumber]; 27 28 if( (r >= 0 && r < BSIZE) && (c >= 0 && c < BSIZE) && !board[r][c] ) { 29 currentRow += vertical[moveNumber]; 30 currentColumn += horizontal[moveNumber]; 31 board[r][c] = i; 32 } 33 } /* end for (i) */ 34 35 moveNumber = 0; 36 for(r = 0; r < BSIZE; r++) { 37 for(c = 0; c < BSIZE; c++) { 38 if(board[r][c]) { 39 printf(" + "); 40 ++moveNumber; 41 } 42 else 43 printf(" - "); 44 } 45 printf("\n"); 46 } 47 printf("Moves: %d\n", moveNumber); 48 49 return 0; 50 } /* E0F main */ 51