1
+ use std:: collections:: HashSet ;
2
+
1
3
use crate :: aoc2024:: Aoc2024 ;
2
4
use crate :: grid:: Grid ;
3
5
use crate :: traits:: days:: Day6 ;
@@ -31,16 +33,32 @@ impl ParseInput<Day6> for Aoc2024 {
31
33
}
32
34
33
35
impl Solution < Day6 > for Aoc2024 {
34
- type Part1Output = u32 ;
36
+ type Part1Output = usize ;
35
37
type Part2Output = u32 ;
36
38
37
- fn part1 ( ( grid, sx, sy) : & ( Grid < bool > , usize , usize ) ) -> u32 {
39
+ fn part1 ( ( grid, sx, sy) : & ( Grid < bool > , usize , usize ) ) -> usize {
40
+ const DIRECTIONS : [ ( isize , isize ) ; 4 ] = [ ( 0 , -1 ) , ( 1 , 0 ) , ( 0 , 1 ) , ( -1 , 0 ) ] ;
41
+
38
42
let ( mut x, mut y) = ( * sx, * sy) ;
39
- let ( mut dx, mut dy) = ( 0 , -1 ) ;
43
+ let mut didx = 0 ;
44
+ let mut positions = HashSet :: new ( ) ;
40
45
41
46
loop {
42
- let ( nx, ny) = ( x. offset ( dx) , y. offset ( dy) ) ;
47
+ positions. insert ( ( x, y) ) ;
48
+ let ( dx, dy) = DIRECTIONS [ didx] ;
49
+ if let Some ( ( nx, ny) ) = offset_pair ( grid, x, y, dx, dy) {
50
+ if * grid. get ( nx, ny) {
51
+ didx = ( didx + 1 ) % 4 ;
52
+ } else {
53
+ x = nx;
54
+ y = ny;
55
+ }
56
+ } else {
57
+ break ;
58
+ }
43
59
}
60
+
61
+ positions. len ( )
44
62
}
45
63
46
64
fn part2 ( _input : & ( Grid < bool > , usize , usize ) ) -> u32 {
@@ -49,9 +67,13 @@ impl Solution<Day6> for Aoc2024 {
49
67
}
50
68
51
69
fn offset_pair ( grid : & Grid < bool > , x : usize , y : usize , dx : isize , dy : isize ) -> Option < ( usize , usize ) > {
52
- let nx = offset ( x, dx, grid. width ) else { return None } ;
53
- let ny = offset ( y, dy, grid. height ) else { return None } ;
54
- ( nx, ny)
70
+ let nx = offset ( x, dx, grid. width ) ;
71
+ let ny = offset ( y, dy, grid. height ) ;
72
+
73
+ match ( nx, ny) {
74
+ ( Some ( nx) , Some ( ny) ) => Some ( ( nx, ny) ) ,
75
+ _ => None ,
76
+ }
55
77
}
56
78
57
79
fn offset ( base : usize , offset : isize , max : usize ) -> Option < usize > {
0 commit comments