training

Code I wrote during training
git clone git://git.bitsmanent.org/training
Log | Files | Refs | README

toth_b.c (1185B)


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