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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
|
use aoc_runner_derive::*;
use std::fmt::{Display, Formatter};
use std::error::Error;
use std::convert::TryFrom;
use std::borrow::Borrow;
#[derive(Eq, PartialEq, Hash, Debug)]
struct Point {
x : usize,
y : usize,
}
#[derive(Eq, Debug)]
pub struct Line {
endpoints : [Point;2]
}
impl PartialEq for Line {
fn eq(&self, other : &Self) -> bool {
(
self.endpoints[0] == other.endpoints[0]
&& self.endpoints[1] == other.endpoints[1]
)
|| (
self.endpoints[1] == other.endpoints[0]
&& self.endpoints[0] == other.endpoints[1]
)
}
}
#[derive(Debug)]
enum AxisAlignedLine {
Horizontal {
start : Point,
length : usize
},
Vertical {
start: Point,
length : usize
}
}
impl AxisAlignedLine {
fn iter(&self) -> AxisAlignedLineIterator<&AxisAlignedLine> {
AxisAlignedLineIterator{
line : self,
index : 0,
}
}
fn into_iter(self) -> AxisAlignedLineIterator<AxisAlignedLine> {
AxisAlignedLineIterator {
line :self,
index : 0,
}
}
}
#[derive(Debug, Clone)]
struct AxisAlignedLineIterator<T>
where T : Borrow<AxisAlignedLine>
{
line : T,
index : usize
}
impl<T> Iterator for AxisAlignedLineIterator<T>
where T : Borrow<AxisAlignedLine>
{
type Item = Point;
fn next(&mut self) -> Option<Point> {
let index = self.index;
match self.line.borrow() {
AxisAlignedLine::Horizontal{ start, length } => {
if index <= *length {
self.index = index + 1;
Some(Point{ x : start.x + index, y: start.y})
} else {
None
}
}
AxisAlignedLine::Vertical{ start, length } => {
if index <= *length {
self.index = index + 1;
Some(Point{x:start.x, y: start.y + index})
}
else {
None
}
}
}
}
}
#[derive(Debug)]
struct NotAxisAlignedError;
impl Display for NotAxisAlignedError {
fn fmt(&self, f: &mut Formatter) -> Result<(), std::fmt::Error> {
write!(f, "Line not axis aligned, cannot be converted to asix aligned line")
}
}
impl Error for NotAxisAlignedError {}
impl TryFrom<&Line> for AxisAlignedLine {
type Error = NotAxisAlignedError;
fn try_from(line : &Line) -> Result<Self,NotAxisAlignedError> {
use std::cmp::{min,max};
if line.endpoints[0].y == line.endpoints[1].y {
let smaller_x = min(line.endpoints[0].x, line.endpoints[1].x);
let larger_x = max(line.endpoints[0].x, line.endpoints[1].x);
Ok(Self::Horizontal{
start : Point { x: smaller_x, y: line.endpoints[0].y },
length : larger_x - smaller_x
})
}
else if line.endpoints[0].x == line.endpoints[1].x {
let smaller_y = min(line.endpoints[0].y, line.endpoints[1].y);
let larger_y = max(line.endpoints[0].y, line.endpoints[1].y);
Ok(Self::Vertical {
start : Point { x: line.endpoints[0].x, y: smaller_y },
length : larger_y - smaller_y
})
}
else {
Err(NotAxisAlignedError)
}
}
}
#[derive(Debug)]
pub enum LineParsingError {
ParseIntError(std::num::ParseIntError),
MalformedLine(String),
MalformedPoint(String),
}
impl From<std::num::ParseIntError> for LineParsingError {
fn from(e : std::num::ParseIntError) -> Self {
LineParsingError::ParseIntError(e)
}
}
impl Display for LineParsingError {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
match self {
LineParsingError::ParseIntError(e) => { e.fmt(f) }
LineParsingError::MalformedLine(s) => {
write!(f, "Line is malformed: {}", s)
}
LineParsingError::MalformedPoint(s) => {
write!(f, "Point is malformed: {}", s)
}
}
}
}
impl Error for LineParsingError {}
fn parse_point_from_string(string : &str) -> Result<Point, LineParsingError> {
if let Some((x, y)) = string.split_once(",") {
x.trim().parse().and_then(|x| y.trim().parse().and_then(|y| Ok(Point {x,y}))).map_err(|e| e.into())
}
else {
Err(LineParsingError::MalformedPoint(string.into()))
}
}
fn parse_line_from_string(string : &str) -> Result<Line, LineParsingError> {
let (parsed_points,index) = string.split("->").map(|string| parse_point_from_string(string))
.try_fold(([None, None],0),|(mut result, index), point| {
if index < 2 {
result[index] = Some(point?);
let index = index + 1;
Ok((result, index))
}
else {
Err(LineParsingError::MalformedLine(string.into()))
}
})?;
if index < 2 {
Err(LineParsingError::MalformedLine(string.into()))
}
else {
Ok(Line {
endpoints : parsed_points.map(|x| x.unwrap()),
})
}
}
#[aoc_generator(day5)]
pub fn input_generator(input : &str) -> Result<Vec<Line>, LineParsingError> {
input.lines()
.map(|string| parse_line_from_string(string))
.try_fold(Vec::new(),|mut result, line| {
line.map(|line| {
result.push(line);
result
})
}
)
}
#[aoc(day5, part1, Plotted)]
pub fn solve_day5_part1_plotted(lines : &Vec<Line>) -> usize {
use std::collections::hash_map::HashMap as Map;
let hit_locations = lines.iter()
.filter_map(|line| line.try_into().ok())
.flat_map(|axis_aligned_line : AxisAlignedLine| axis_aligned_line.into_iter());
let hit_counts = hit_locations.fold(Map::new(), |mut map, point| {
map.entry(point).and_modify(|x| *x+=1).or_insert(1);
map
});
hit_counts.iter().filter(|(_, value)| **value >= 2).count()
}
#[cfg(test)]
mod day5_tests{
use super::*;
fn get_day5_string_testdata() -> &'static str {
r#"0,9 -> 5,9
8,0 -> 0,8
9,4 -> 3,4
2,2 -> 2,1
7,0 -> 7,4
6,4 -> 2,0
0,9 -> 2,9
3,4 -> 1,4
0,0 -> 8,8
5,5 -> 8,2"#
}
fn get_day5_parsed_testdata() -> Vec<Line> {
vec!{
Line{endpoints:[Point{x:0,y:9},Point{x:5,y:9}]},
Line{endpoints:[Point{x:8,y:0},Point{x:0,y:8}]},
Line{endpoints:[Point{x:9,y:4},Point{x:3,y:4}]},
Line{endpoints:[Point{x:2,y:2},Point{x:2,y:1}]},
Line{endpoints:[Point{x:7,y:0},Point{x:7,y:4}]},
Line{endpoints:[Point{x:6,y:4},Point{x:2,y:0}]},
Line{endpoints:[Point{x:0,y:9},Point{x:2,y:9}]},
Line{endpoints:[Point{x:3,y:4},Point{x:1,y:4}]},
Line{endpoints:[Point{x:0,y:0},Point{x:8,y:8}]},
Line{endpoints:[Point{x:5,y:5},Point{x:8,y:2}]},
}
}
#[test]
fn test_day5_input_generator() {
let parse_result = input_generator(get_day5_string_testdata()).unwrap();
assert_eq!(parse_result, get_day5_parsed_testdata())
}
#[test]
fn test_day5_part1_solution_plotted() {
assert_eq!(solve_day5_part1_plotted(&get_day5_parsed_testdata()), 5)
}
}
|