training

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

toth_c.c (2122B)


      1 /* Exercise 6.24 (c) */
      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    /* Method "heuristic of accessibility" */
     15    int accessibility[BSIZE][BSIZE] = {
     16       { 2, 3, 4, 4, 4, 4, 3, 2 },
     17       { 3, 4, 6, 6, 6, 6, 4, 3 },
     18       { 4, 6, 8, 8, 8, 8, 6, 4 },
     19       { 4, 6, 8, 8, 8, 8, 6, 4 },
     20       { 4, 6, 8, 8, 8, 8, 6, 4 },
     21       { 4, 6, 8, 8, 8, 8, 6, 4 },
     22       { 3, 4, 6, 6, 6, 6, 4, 3 },
     23       { 2, 3, 4, 4, 4, 4, 3, 2 }
     24    };
     25 
     26    /* next position according with the "accessibility" matrix */
     27    int new_r, new_c;
     28 
     29    int cal; /* current accessibility level */
     30    int pass = 0; /* write permission checker :-) */
     31 
     32    int moveNumber = 0, i, r, c;
     33    int currentRow = 0, currentColumn = 0;
     34    board[currentRow][currentColumn] = -1; /* current position */
     35 
     36    for(i = 1; i <= BSIZE*BSIZE; i++) {
     37       cal = BSIZE;
     38       for(moveNumber = 0; moveNumber < BSIZE; moveNumber++) {
     39 
     40          /* read next potential position */
     41          r = currentRow + vertical[moveNumber];
     42          c = currentColumn + horizontal[moveNumber];
     43 
     44          /* it's not out of chessboard */
     45          if( (r >= 0 && r < BSIZE) && (c >= 0 && c < BSIZE) && !board[r][c] ) {
     46 	    pass = 1; /* write access granted :-) */
     47 
     48 	    /* check accessibility level */
     49 	    if(accessibility[r][c] < cal) {
     50 	       new_r = r;
     51 	       new_c = c;
     52 	       cal = accessibility[new_r][new_c];
     53 	    }
     54 	 }
     55       } /* end for (moveNumber) */
     56 
     57       if(pass) {
     58 	 currentRow = new_r;
     59 	 currentColumn = new_c;
     60 	 --accessibility[new_r][new_c];
     61          board[currentRow][currentColumn] = i;
     62 	 pass = 0;
     63       }
     64       else /* stalled */
     65 	 break;
     66    } /* end for (i) */
     67 
     68    moveNumber = 0;
     69    for(r = 0; r < BSIZE; r++) {
     70       for(c = 0; c < BSIZE; c++) {
     71 	 if(board[r][c]) {
     72 	    printf("+");
     73 	    ++moveNumber;
     74 	 }
     75 	 else
     76 	    printf("-");
     77       }
     78       printf("\n");
     79    }
     80    printf("Moves: %d\n", moveNumber);
     81 
     82    return 0;
     83 } /* E0F main */
     84