1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#[derive(Debug, Copy, Clone)]
pub enum Direction {
Up,
Down,
Left,
Right,
}
pub trait CanTravel<T> {
fn travel(&self, from: &T) -> T;
fn travel_checked(&self, from: &T) -> Option<T>;
}
impl Direction {
pub fn turn_left(&self) -> Direction {
match self {
Direction::Up => Direction::Left,
Direction::Down => Direction::Right,
Direction::Left => Direction::Down,
Direction::Right => Direction::Up,
}
}
pub fn turn_right(&self) -> Direction {
match self {
Direction::Up => Direction::Right,
Direction::Down => Direction::Left,
Direction::Left => Direction::Up,
Direction::Right => Direction::Down,
}
}
pub fn reverse(&self) -> Direction {
match self {
Direction::Up => Direction::Down,
Direction::Down => Direction::Up,
Direction::Left => Direction::Right,
Direction::Right => Direction::Left,
}
}
pub fn turn(&self, steps: isize) -> Direction {
let actual_steps = steps.rem_euclid(4);
match actual_steps {
0 => *self,
1 => self.turn_left(),
2 => self.reverse(),
3 => self.turn_right(),
_ => unreachable!(),
}
}
}
impl CanTravel<(i64, i64)> for Direction {
fn travel(&self, (x, y): &(i64, i64)) -> (i64, i64) {
match self {
Direction::Up => (*x, *y - 1),
Direction::Down => (*x, *y + 1),
Direction::Left => (*x - 1, *y),
Direction::Right => (*x + 1, *y),
}
}
fn travel_checked(&self, from: &(i64, i64)) -> Option<(i64, i64)> {
Some(self.travel(from))
}
}
impl CanTravel<(usize, usize)> for Direction {
fn travel(&self, (x, y): &(usize, usize)) -> (usize, usize) {
match self {
Direction::Up => (*x, *y - 1),
Direction::Down => (*x, *y + 1),
Direction::Left => (*x - 1, *y),
Direction::Right => (*x + 1, *y),
}
}
fn travel_checked(&self, (x, y): &(usize, usize)) -> Option<(usize, usize)> {
match self {
Direction::Up if *y == 0 => None,
Direction::Up => Some((*x, *y - 1)),
Direction::Down => Some((*x, *y + 1)),
Direction::Left if *x == 0 => None,
Direction::Left => Some((*x - 1, *y)),
Direction::Right => Some((*x + 1, *y)),
}
}
}