-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday1.rs
68 lines (64 loc) · 1.56 KB
/
day1.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
use crate::Input;
use str_block::str_block;
pub fn inputs() -> Vec<Input> {
vec![
Input::Hashed("bd3e2df596a877265fe4a28b626ac1ed30239c051e6623b4c852be317288fe1a"),
Input::Inline(
"example",
str_block! {"
3 4
4 3
2 5
1 3
3 9
3 3
"},
Some(11),
Some(31),
),
]
}
fn parse_line(s: &str) -> (u32, u32) {
let mut l = 0;
let mut r = 0;
let mut bytes = s.as_bytes().iter().copied();
for b in bytes.by_ref() {
let v = b.wrapping_sub(b'0');
if v > 9 {
break;
}
l = l * 10 + v as u32;
}
bytes.next();
bytes.next();
for b in bytes {
let v = b.wrapping_sub(b'0');
r = r * 10 + v as u32;
}
(l, r)
}
pub fn part1(input: &str) -> u32 {
let mut left = Vec::with_capacity(1000);
let mut right = Vec::with_capacity(1000);
for line in input.lines() {
let (l, r) = parse_line(line);
left.push(l);
right.push(r);
}
left.sort_unstable();
right.sort_unstable();
left.into_iter()
.zip(right)
.map(|(l, r)| l.abs_diff(r))
.sum()
}
pub fn part2(input: &str) -> u32 {
let mut left = Vec::with_capacity(1000);
let mut right = vec![0; 100_000];
for line in input.lines() {
let (l, r) = parse_line(line);
left.push(l);
right[r as usize] += 1;
}
left.into_iter().map(|i| i * right[i as usize]).sum()
}