From 9608d466d4b0693c21825b9c1df3ba01b13aba44 Mon Sep 17 00:00:00 2001 From: Mariano Riefolo Date: Thu, 15 Aug 2024 21:45:17 +0200 Subject: [PATCH] Updated program for Day 21 The maze is more random --- .../day21/src/lib.rs | 55 +++++++++++-------- 1 file changed, 31 insertions(+), 24 deletions(-) diff --git a/Week-03/Day-21_Random-Maze-Generator/day21/src/lib.rs b/Week-03/Day-21_Random-Maze-Generator/day21/src/lib.rs index 8c356b1..c16728a 100644 --- a/Week-03/Day-21_Random-Maze-Generator/day21/src/lib.rs +++ b/Week-03/Day-21_Random-Maze-Generator/day21/src/lib.rs @@ -10,6 +10,7 @@ pub fn draw_maze(height: usize, width: usize) -> String { rng.random_number(0, width as u128) as usize, ), &mut maze, + &mut rng, ); let mut res = "+---".repeat(width) + "+"; @@ -36,32 +37,38 @@ pub fn draw_maze(height: usize, width: usize) -> String { res } -fn bfs_make_maze(position: (usize, usize), maze: &mut Vec>) { +fn bfs_make_maze(position: (usize, usize), maze: &mut Vec>, rng: &mut Rng) { maze[position.0][position.1].2 = true; - if position.1 + 1 < maze[0].len() && !maze[position.0][position.1 + 1].2 { - let mut new_position = position; - new_position.1 += 1; - maze[position.0][position.1].1 = true; - bfs_make_maze(new_position, maze); + let mut nums = [0, 1, 2, 3]; + for i in (0..4).rev() { + let rand_index = rng.random_number(0, i + 1); + nums.swap(rand_index as usize, i as usize); } - - if position.1 > 0 && !maze[position.0][position.1 - 1].2 { - let mut new_position = position; - new_position.1 -= 1; - maze[new_position.0][new_position.1].1 = true; - bfs_make_maze(new_position, maze); - } - if position.0 + 1 < maze.len() && !maze[position.0 + 1][position.1].2 { - let mut new_position = position; - new_position.0 += 1; - maze[position.0][position.1].0 = true; - bfs_make_maze(new_position, maze); - } - if position.0 > 0 && !maze[position.0 - 1][position.1].2 { - let mut new_position = position; - new_position.0 -= 1; - maze[new_position.0][new_position.1].0 = true; - bfs_make_maze(new_position, maze); + for num in nums { + if num == 0 && position.1 + 1 < maze[0].len() && !maze[position.0][position.1 + 1].2 { + let mut new_position = position; + new_position.1 += 1; + maze[position.0][position.1].1 = true; + bfs_make_maze(new_position, maze, rng); + } + if num == 1 && position.1 > 0 && !maze[position.0][position.1 - 1].2 { + let mut new_position = position; + new_position.1 -= 1; + maze[new_position.0][new_position.1].1 = true; + bfs_make_maze(new_position, maze, rng); + } + if num == 2 && position.0 + 1 < maze.len() && !maze[position.0 + 1][position.1].2 { + let mut new_position = position; + new_position.0 += 1; + maze[position.0][position.1].0 = true; + bfs_make_maze(new_position, maze, rng); + } + if num == 3 && position.0 > 0 && !maze[position.0 - 1][position.1].2 { + let mut new_position = position; + new_position.0 -= 1; + maze[new_position.0][new_position.1].0 = true; + bfs_make_maze(new_position, maze, rng); + } } }