-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday2.rs
150 lines (136 loc) · 3.69 KB
/
day2.rs
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
//! [Day 2: Bathroom Security](https://adventofcode.com/2016/day/2)
pub fn main() {
let args = aoc::parse_args();
args.run(solve);
}
/// # Panics
#[must_use]
pub fn solve(data: &str) -> (String, String) {
(part1(data), part2(data))
}
/// part 1
fn part1(data: &str) -> String {
let mut bathroom_code = String::new();
let mut x = 1_u8; // position on the 3x3 grid
let mut y = 1_u8; // starting at the middle of the grid
for line in data.lines() {
for c in line.chars() {
match c {
'U' => y = y.saturating_sub(1),
'D' => {
if y < 2 {
y += 1;
}
}
'L' => x = x.saturating_sub(1),
'R' => {
if x < 2 {
x += 1;
}
}
_ => panic!("unknown direction: {c}"),
}
}
let key = (x + y * 3 + b'1') as char;
bathroom_code.push(key);
}
bathroom_code
}
/// part 2
fn part2(data: &str) -> String {
let mut bathroom_code = String::new();
let mut pos = '5';
for line in data.lines() {
for c in line.chars() {
pos = match pos {
'1' => match c {
'D' => '3',
_ => pos,
},
'2' => match c {
'D' => '6',
'R' => '3',
_ => pos,
},
'3' => match c {
'U' => '1',
'D' => '7',
'L' => '2',
'R' => '4',
_ => pos,
},
'4' => match c {
'D' => '8',
'L' => '3',
_ => pos,
},
'5' => match c {
'R' => '6',
_ => pos,
},
'6' => match c {
'U' => '2',
'D' => 'A',
'L' => '5',
'R' => '7',
_ => pos,
},
'7' => match c {
'U' => '3',
'D' => 'B',
'L' => '6',
'R' => '8',
_ => pos,
},
'8' => match c {
'U' => '4',
'D' => 'C',
'L' => '7',
'R' => '9',
_ => pos,
},
'9' => match c {
'L' => '8',
_ => pos,
},
'A' => match c {
'U' => '6',
'R' => 'B',
_ => pos,
},
'B' => match c {
'U' => '7',
'D' => 'D',
'L' => 'A',
'R' => 'C',
_ => pos,
},
'C' => match c {
'U' => '8',
'L' => 'B',
_ => pos,
},
'D' => match c {
'U' => 'B',
_ => pos,
},
_ => panic!("unknown position: {pos}"),
}
}
bathroom_code.push(pos);
}
bathroom_code
}
#[cfg(test)]
mod test {
use super::*;
const TEST_INPUT: &str = include_str!("test.txt");
#[test]
fn test_part1() {
assert_eq!(part1(TEST_INPUT), "1985");
}
#[test]
fn test_part2() {
assert_eq!(part2(TEST_INPUT), "5DB3");
}
}