This repository has been archived by the owner. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.rs
84 lines (73 loc) · 1.69 KB
/
lib.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
pub fn part1(input: &str) -> u32 {
input
.as_bytes()
.iter()
.chain(&[b'\n'; 2]) // Avoid having custom logic for the last group.
.fold((0, 0, 0), |(max, sum, curr), b| {
if *b == b'\n' {
if curr == 0 {
(max.max(sum), 0, 0)
} else {
(max, sum + curr, 0)
}
} else {
(max, sum, curr * 10 + (*b - b'0') as u32)
}
})
.0
}
pub fn part2(input: &str) -> u32 {
let s = input
.as_bytes()
.iter()
.chain(&[b'\n'; 2]) // Avoid having custom logic for the last group.
.fold(((0, 0, 0), 0, 0), |(top3, sum, curr), b| {
if *b == b'\n' {
if curr == 0 {
(insert_max(top3, sum), 0, 0)
} else {
(top3, sum + curr, 0)
}
} else {
(top3, sum, curr * 10 + (*b - b'0') as u32)
}
})
.0;
s.0 + s.1 + s.2
}
fn insert_max(top3: (u32, u32, u32), e: u32) -> (u32, u32, u32) {
if e < top3.2 {
top3
} else if e < top3.1 {
(top3.0, top3.1, e)
} else if e < top3.0 {
(top3.0, e, top3.1)
} else {
(e, top3.0, top3.1)
}
}
pub fn run_part1() {
println!("{}", part1(include_str!("../input")));
}
pub fn run_part2() {
println!("{}", part2(include_str!("../input")));
}
#[cfg(test)]
mod tests {
use crate::*;
#[test]
fn example() {
let input = "1000
2000
3000
4000
5000
6000
7000
8000
9000
10000";
assert_eq!(24000, part1(&input));
assert_eq!(45000, part2(&input));
}
}