From 7b108cc087650ce47113a4dd17d8d192a795825e Mon Sep 17 00:00:00 2001 From: Shaquille Soekhlal Date: Thu, 11 Mar 2021 19:06:57 +0000 Subject: [PATCH] Add 'Week 4/D2 - 2' --- Week 4/D2 - 2 | 71 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 Week 4/D2 - 2 diff --git a/Week 4/D2 - 2 b/Week 4/D2 - 2 new file mode 100644 index 0000000..9624875 --- /dev/null +++ b/Week 4/D2 - 2 @@ -0,0 +1,71 @@ +#include +#include +#include +#include +#include + +enum direction { // so up, etc can be used in functions, compile time constants + up = -10, + left = -1, + down = 10, + right = 1 +}; + +int is_valid_dir(char *array, int index, int dir) { + switch (dir) { + case up: + return (index > 10 && *(array + index + dir) == '.'); // if pos isnt topmost, and above is . + case left: + return (index % 10 && *(array + index + dir) == '.'); // if pos isn't leftmost, and left isn't "." + case down: + return (index < 90 && *(array + index + 10) == '.'); //if pos isn't downmost, and down isn't "." + case right: + return (index % 10 != 9 && *(array + index + dir) == '.'); + default: + return false; + } +} + +bool is_stuck(char *arr, int index) { + return !(*(arr + index + up) == '.' || + *(arr + index + down) == '.' || + *(arr + index + left) == '.' || + *(arr + index + right) == '.' + ); +} + +int main() { + srand(time(0)); // seed rand + int direction[4] = {-10, -1, 10, 1}; // to convert rand output to a position change + // generate maze + char maze_[10][10] = {}; + + for (int i = 0; i < 10; i++) { // the 2d way + for (int j = 0; j < 10; j++) { + maze_[i][j] = '.'; + } + } + char *maze = &maze_; + char character = 'A'; + int pos = 0; + maze[pos] = character; + // traverse maze + for (int i = 0; i < 25; i++) { + int dir = direction[rand() % 4]; + while (!is_valid_dir(maze, pos, dir) && !is_stuck(maze, pos)) { + dir = direction[rand() % 4]; + } + if (is_stuck(maze, pos)) { + printf("Got myself in a sticky situation\n"); + break; + } + pos += dir; + maze[pos] = ++character; + } + for (int i = 0; i < 100; i++) { + printf("%c", maze[i]); + if (i % 10 == 9) { + printf("\n"); + } + } +} \ No newline at end of file