training

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

toth_rand2.c (1720B)


      1 /* Exercise 6.25 (c) */
      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, currentColumn;
     18 
     19    int clen[20] = { 0 }; /* max integer size */
     20    long int test = 0; /* total tests */
     21    int n = 0; /* tests where x < y */
     22 
     23    srand( time(NULL) );
     24 
     25    while(moveNumber < 64) {
     26       ++test;
     27 
     28       currentRow = currentColumn = 0;
     29       board[currentRow][currentColumn] = -1; /* current position */
     30       for(i = 1; i <= BSIZE*BSIZE; ++i) {
     31 	    moveNumber = rand() % 8;
     32 
     33             r = currentRow + vertical[moveNumber];
     34             c = currentColumn + horizontal[moveNumber];
     35 
     36             if( (r >= 0 && r < BSIZE) && (c >= 0 && c < BSIZE) &&
     37 		 !board[r][c] ) {
     38 	       currentRow += vertical[moveNumber];
     39 	       currentColumn += horizontal[moveNumber];
     40                board[r][c] = i;
     41 	    }
     42 	    
     43       } /* end for (i) */
     44 
     45       moveNumber = 0;
     46       for(r = 0; r < BSIZE; r++) {
     47          for(c = 0; c < BSIZE; c++) {
     48 	    if(board[r][c]) {
     49 	       ++moveNumber;
     50                board[r][c] = 0;
     51 	    }
     52 	 }
     53       }
     54 
     55       if(moveNumber > clen[n-1])
     56 	 clen[n++] = moveNumber;
     57 
     58       if(n == 20) {
     59 	 printf("Out of limit!\n");
     60 	 return -1;
     61       }
     62    } /* end while (moveNumber) */
     63 
     64    printf("Turns: %ld\n", test); /* total turns */
     65 
     66    /* print the table */
     67    for( ; n > 1; n--) {
     68       printf("%d=%d\t", n, clen[n]);
     69       if( !(n % 10) ) {
     70          printf("\n");
     71       }
     72    }
     73 
     74    return 0;
     75 } /* E0F main */
     76