c - MultiDimensional Array randomly hanging -
i have program have been working on day. program freezes more times doesn't freeze....when doesn't freeze works fine , looks this... http://picpaste.com/multidimensional_array-kfdksmoe.bmp
when hang upon opening this... http://picpaste.com/multidimensional_array_hung-jcmz0rqp.bmp
// chapter 8 programming project #9 #include <stdio.h> #include <stdbool.h> #include <stdlib.h> #include <time.h> #define size 10 #define path_size 25 #define row_size ((int) (sizeof(board) / sizeof(board[0]))) int main(void) { char board[size][size] = {}; // 0 = up, 1 = down, 2 = left, 3 = right unsigned short = 0, x, y; // generate random number srand((unsigned) time(null)); int dir = rand() % 4; // set positions of board '.' (x = 0; x < row_size; x++) { (y = 0; y < row_size; y++) board[x][y] = '.'; } x = 0; y = 0; board[0][0] = 'a'; // generate path while (i != path_size) { (i = 0; < path_size;) { // check direction , replace char switch (dir) { case 0: if ((y - 1) >= 0 && (y - 1) < row_size && board[x][y - 1] == '.') { board[x][--y] = + 'b'; ++i; } break; case 1: if ((y + 1) >= 0 &&(y + 1) < row_size && board[x][y + 1] == '.') { board[x][++y] = + 'b'; ++i; } break; case 2: if ((x - 1) >= 0 && (x - 1) < row_size && board[x - 1][y] == '.') { board[--x][y] = + 'b'; ++i; } break; case 3: if ((x + 1) >= 0 && (x + 1) < row_size && board[x + 1][y] == '.') { board[++x][y] = + 'b'; ++i; } break; } // reset random direction dir = rand() % 4; } } // print board (x = 0; x < row_size; x++) { (y = 0; y < row_size; y++) printf("%c ", board[x][y]); printf("\n"); } return 0; }
this hang when there no possible directions move. taking simple example of board 4 4. board like
.... .... .... .... initial position marked
a... .... .... .... i make first move, move right
ab.. .... .... .... i make next move, move down
ab.. .c.. .... .... i make next move, move down
ab.. .c.. .d.. .... i make next move, move left
ab.. .c.. ed.. .... i make next move, move up
ab.. fc.. ed.. .... and stuck, , not have possible locations move. few more additions fix problem.
- add method calculate list of possible moving directions
- if no more moves possible, exit program
hint
void calc_poss_dirs() { int dir; poss_dir.count = 0; (dir = up; dir <= right; dir++) { if (can_move(dir)) { poss_dir.dirs[poss_dir.count] = dir; poss_dir.count++; } } } int can_move(int dir) { int x = cur_x; int y = cur_y; if (dir == up) x--; else if (dir == down) x++; else if (dir == left) y--; else y++; if (!in_area(x, y)) return 0; if (visited(x, y)) return 0; return 1; }
Comments
Post a Comment