1+ use crate :: grid:: { Compass , ORIGIN , Pos } ;
12use std:: collections:: HashSet ;
23
34pub struct Solver {
@@ -31,7 +32,7 @@ fn part1(input: &[Instruction]) -> u32 {
3132
3233fn part2 ( input : & [ Instruction ] ) -> u32 {
3334 let mut state = State :: new ( ) ;
34- let mut visited: HashSet < ( i32 , i32 ) > = HashSet :: new ( ) ;
35+ let mut visited: HashSet < Pos > = HashSet :: new ( ) ;
3536 for instruction in input {
3637 state. turn ( instruction. turn ) ;
3738 for _ in 0 ..instruction. walk {
@@ -45,61 +46,32 @@ fn part2(input: &[Instruction]) -> u32 {
4546 panic ! ( "Didn't visit any location twice" )
4647}
4748
48- #[ derive( Clone , Copy ) ]
49- enum Direction {
50- North ,
51- East ,
52- South ,
53- West ,
54- }
55-
56- impl Direction {
57- fn turn ( & self , turn : Turn ) -> Direction {
58- match turn {
59- Turn :: Left => match self {
60- Direction :: North => Direction :: West ,
61- Direction :: East => Direction :: North ,
62- Direction :: South => Direction :: East ,
63- Direction :: West => Direction :: South ,
64- } ,
65- Turn :: Right => match self {
66- Direction :: North => Direction :: East ,
67- Direction :: East => Direction :: South ,
68- Direction :: South => Direction :: West ,
69- Direction :: West => Direction :: North ,
70- } ,
71- }
72- }
73- }
74-
7549struct State {
76- direction : Direction ,
77- position : ( i32 , i32 ) ,
50+ direction : Compass ,
51+ position : Pos ,
7852}
7953
8054impl State {
8155 fn new ( ) -> Self {
8256 Self {
83- direction : Direction :: North ,
84- position : ( 0 , 0 ) ,
57+ direction : Compass :: North ,
58+ position : ORIGIN ,
8559 }
8660 }
8761
8862 fn turn ( & mut self , turn : Turn ) {
89- self . direction = self . direction . turn ( turn) ;
63+ self . direction = match turn {
64+ Turn :: Left => self . direction . left90 ( ) ,
65+ Turn :: Right => self . direction . right90 ( ) ,
66+ }
9067 }
9168
9269 fn walk ( & mut self , walk : u32 ) {
93- match self . direction {
94- Direction :: North => self . position . 1 += walk as i32 ,
95- Direction :: East => self . position . 0 += walk as i32 ,
96- Direction :: South => self . position . 1 -= walk as i32 ,
97- Direction :: West => self . position . 0 -= walk as i32 ,
98- } ;
70+ self . position = self . position . walk ( self . direction , walk as i32 ) ;
9971 }
10072
10173 fn distance_from_origin ( & self ) -> u32 {
102- self . position . 0 . unsigned_abs ( ) + self . position . 1 . unsigned_abs ( )
74+ self . position . manhattan_distance ( & ORIGIN )
10375 }
10476}
10577
0 commit comments