Skip to content

Commit 6c06c4c

Browse files
committed
refactor(01/2015): make code more rusty
1 parent 3f7ef02 commit 6c06c4c

File tree

1 file changed

+24
-19
lines changed

1 file changed

+24
-19
lines changed

src/solutions/year2015/day01.rs

Lines changed: 24 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,41 @@
11
use crate::solutions::Solution;
22

3+
const BASEMENT: isize = -1;
4+
35
pub struct Day01;
46

57
impl Solution for Day01 {
68
fn part_one(&self, input: &str) -> String {
79
input
810
.bytes()
9-
.map(|b| match b {
10-
b'(' => 1,
11-
b')' => -1,
12-
_ => 0,
13-
})
11+
.map(Day01::map_byte)
1412
.sum::<isize>()
1513
.to_string()
1614
}
1715

1816
fn part_two(&self, input: &str) -> String {
19-
let mut current_flor = 0;
20-
21-
for (i, b) in input.bytes().enumerate() {
22-
current_flor += match b {
23-
b'(' => 1,
24-
b')' => -1,
25-
_ => 0,
26-
};
27-
28-
if current_flor == -1 {
29-
return (i + 1).to_string();
30-
}
31-
}
17+
input
18+
.bytes()
19+
.map(Day01::map_byte)
20+
.scan(0, |floor, change| {
21+
*floor += change;
3222

33-
unreachable!()
23+
Some(*floor)
24+
})
25+
.position(|floor| floor == BASEMENT)
26+
.map(|i| i + 1)
27+
.unwrap()
28+
.to_string()
29+
}
30+
}
31+
32+
impl Day01 {
33+
fn map_byte(b: u8) -> isize {
34+
match b {
35+
b'(' => 1,
36+
b')' => -1,
37+
_ => 0,
38+
}
3439
}
3540
}
3641

0 commit comments

Comments
 (0)