Skip to content

Commit

Permalink
Year 2024, Day 06
Browse files Browse the repository at this point in the history
  • Loading branch information
kurisuke committed Dec 6, 2024
1 parent beb1da2 commit e4b47c3
Show file tree
Hide file tree
Showing 2 changed files with 106 additions and 0 deletions.
104 changes: 104 additions & 0 deletions year2024/src/day06.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
use std::collections::HashSet;

use common::day::Day;
use util::grid2d::{Coords, Direction, Grid2D};

pub struct Day06 {}

impl Day for Day06 {
fn star1(&self, input: &str) -> String {
let grid = Grid2D::new(input).unwrap();
let visited = walk(grid).unwrap();
let visited: HashSet<_> = visited.into_iter().map(|g| g.pos).collect();
format!("{}", visited.len())
}

fn star2(&self, input: &str) -> String {
let grid = Grid2D::new(input).unwrap();
let empty_pos = grid.filter(&['.']);

let mut num_loop_pos = 0;
for add_pos in empty_pos {
let mut grid_add = grid.clone();
grid_add.set(&add_pos, '#');
if walk(grid_add).is_err() {
num_loop_pos += 1;
}
}
format!("{}", num_loop_pos)
}
}

#[derive(Copy, Clone, Hash, PartialEq, Eq, Debug)]
struct Guard {
pos: Coords,
dir: Direction,
}

fn walk(mut grid: Grid2D<char>) -> Result<HashSet<Guard>, Guard> {
let pos = grid.find('^').unwrap();
let mut guard = Guard {
pos,
dir: Direction::N,
};

let mut visited = HashSet::new();
visited.insert(guard);
grid.set(&pos, '.');

loop {
let check_pos = guard.pos.mov(guard.dir);
if let Some(v) = grid.at(&check_pos) {
match v {
'#' => {
guard.dir = match guard.dir {
Direction::N => Direction::E,
Direction::E => Direction::S,
Direction::S => Direction::W,
Direction::W => Direction::N,
_ => unreachable!(),
};
}
'.' => {
guard.pos = check_pos;
if !visited.insert(guard) {
return Err(guard);
}
}
_ => unreachable!(),
}
} else {
break;
}
}

Ok(visited)
}

#[cfg(test)]
mod tests {
use super::*;

const INPUT: &str = r#"....#.....
.........#
..........
..#.......
.......#..
..........
.#..^.....
........#.
#.........
......#..."#;

#[test]
fn star1() {
let d = Day06 {};
assert_eq!(d.star1(INPUT), "41");
}

#[test]
fn star2() {
let d = Day06 {};
assert_eq!(d.star2(INPUT), "6");
}
}
2 changes: 2 additions & 0 deletions year2024/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ mod day02;
mod day03;
mod day04;
mod day05;
mod day06;

pub struct Year2024 {}

Expand All @@ -17,6 +18,7 @@ impl Year for Year2024 {
3 => Some(Box::new(day03::Day03 {})),
4 => Some(Box::new(day04::Day04 {})),
5 => Some(Box::new(day05::Day05 {})),
6 => Some(Box::new(day06::Day06 {})),
_ => None,
}
}
Expand Down

0 comments on commit e4b47c3

Please sign in to comment.