Skip to content

Commit bebf7a5

Browse files
committed
refactor(03/2015): extract common logic to one method
1 parent 3c475f5 commit bebf7a5

File tree

1 file changed

+16
-28
lines changed

1 file changed

+16
-28
lines changed

src/solutions/year2015/day03.rs

Lines changed: 16 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -8,46 +8,34 @@ pub struct Day03;
88

99
impl Solution for Day03 {
1010
fn part_one(&self, input: &str) -> String {
11-
let mut visited_houses: Houses = HashMap::new();
12-
let mut santa = Point::new(0, 0);
13-
visited_houses.insert(santa, 1);
14-
15-
for b in input.bytes() {
16-
santa = self.make_move(santa, b);
17-
18-
self.visit_house(&mut visited_houses, santa);
19-
}
20-
21-
visited_houses.len().to_string()
11+
self.solve(input, 1).to_string()
2212
}
2313

2414
fn part_two(&self, input: &str) -> String {
15+
self.solve(input, 2).to_string()
16+
}
17+
}
18+
19+
impl Day03 {
20+
fn solve(&self, input: &str, santas: usize) -> usize {
2521
let mut visited_houses: Houses = HashMap::new();
26-
let mut santa = Point::new(0, 0);
27-
visited_houses.insert(santa, 1);
22+
let mut santas = vec![Point::new(0, 0); santas];
2823

29-
let mut robo_santa = Point::new(0, 0);
30-
visited_houses.insert(robo_santa, 1);
24+
for santa in &santas {
25+
visited_houses.insert(*santa, 1);
26+
}
3127

3228
for (i, b) in input.bytes().enumerate() {
33-
let visited = if i % 2 == 0 {
34-
santa = self.make_move(santa, b);
29+
let index = i % santas.len();
3530

36-
santa
37-
} else {
38-
robo_santa = self.make_move(robo_santa, b);
31+
santas[index] = self.make_move(santas[index], b);
3932

40-
robo_santa
41-
};
42-
43-
self.visit_house(&mut visited_houses, visited);
33+
self.visit_house(&mut visited_houses, santas[index]);
4434
}
4535

46-
visited_houses.len().to_string()
36+
visited_houses.len()
4737
}
48-
}
4938

50-
impl Day03 {
5139
fn make_move(&self, point: Point, b: u8) -> Point {
5240
match b {
5341
b'>' => point.east(),
@@ -59,7 +47,7 @@ impl Day03 {
5947
}
6048

6149
fn visit_house(&self, houses: &mut Houses, house: Point) {
62-
houses.entry(house).and_modify(|e| *e += 1).or_insert(1);
50+
*houses.entry(house).or_default() += 1
6351
}
6452
}
6553

0 commit comments

Comments
 (0)