Skip to content

Commit 5d4fc47

Browse files
committed
refactor(01/2016): make it more functional
1 parent f52b72f commit 5d4fc47

File tree

1 file changed

+31
-23
lines changed

1 file changed

+31
-23
lines changed

src/solutions/year2016/day01.rs

Lines changed: 31 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -10,35 +10,23 @@ pub struct Day01;
1010
impl Solution for Day01 {
1111
fn part_one(&self, input: &str) -> String {
1212
let start = Point::new(0, 0);
13-
let mut vector = Vector::new(start, Direction::North);
14-
15-
self.parse(input.trim()).for_each(|(rotation, distance)| {
16-
vector = vector.rotate(rotation).forward_with_length(distance);
17-
});
1813

19-
vector.position().manhattan_distance(&start).to_string()
14+
self.parse(input.trim())
15+
.fold(Vector::new(start, Direction::North), |vector, (r, d)| {
16+
vector.rotate(r).forward_with_length(d)
17+
})
18+
.position()
19+
.manhattan_distance(&start)
20+
.to_string()
2021
}
2122

2223
fn part_two(&self, input: &str) -> String {
2324
let start = Point::new(0, 0);
24-
let mut vector = Vector::new(start, Direction::North);
25-
26-
let mut visited = HashSet::new();
27-
visited.insert(start);
28-
29-
'outer: for (rotation, distance) in self.parse(input.trim()) {
30-
vector = vector.rotate(rotation);
31-
32-
for _ in 0..distance {
33-
vector = vector.forward();
34-
35-
if !visited.insert(vector.position()) {
36-
break 'outer;
37-
}
38-
}
39-
}
4025

41-
vector.position().manhattan_distance(&start).to_string()
26+
self.find_first_revisit(input.trim(), start)
27+
.unwrap()
28+
.manhattan_distance(&start)
29+
.to_string()
4230
}
4331
}
4432

@@ -56,6 +44,26 @@ impl Day01 {
5644
(rotation, distance)
5745
})
5846
}
47+
48+
fn find_first_revisit(&self, input: &str, start: Point) -> Option<Point> {
49+
let mut vector = Vector::new(start, Direction::North);
50+
let mut visited = HashSet::new();
51+
visited.insert(start);
52+
53+
for (rotation, distance) in self.parse(input) {
54+
vector = vector.rotate(rotation);
55+
56+
for _ in 0..distance {
57+
vector = vector.forward();
58+
59+
if !visited.insert(vector.position()) {
60+
return Some(vector.position());
61+
}
62+
}
63+
}
64+
65+
None
66+
}
5967
}
6068

6169
#[cfg(test)]

0 commit comments

Comments
 (0)