-
Notifications
You must be signed in to change notification settings - Fork 0
/
13.rs
67 lines (59 loc) · 1.52 KB
/
13.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
#![feature(test)]
use itertools::Itertools;
type Input = Vec<Machine>;
#[derive(Debug, Clone, Copy)]
struct Machine {
a: (i64, i64),
b: (i64, i64),
prize: (i64, i64),
}
fn setup(input: &str) -> Input {
input
.trim()
.split("\n\n")
.map(|block| {
let mut lines = block.lines().map(|l| {
l.split(|c: char| !matches!(c, '0'..='9' | '-'))
.filter(|s| !s.is_empty())
.map(|n| n.parse().unwrap())
.collect_tuple()
.unwrap()
});
Machine {
a: lines.next().unwrap(),
b: lines.next().unwrap(),
prize: lines.next().unwrap(),
}
})
.collect()
}
fn solve(
Machine {
a: (ax, ay),
b: (bx, by),
prize: (px, py),
}: Machine,
) -> Option<i64> {
let a = (py * bx - px * by) / (bx * ay - ax * by);
let b = (py * ax - px * ay) / (ax * by - bx * ay);
(a * ax + b * bx == px && a * ay + b * by == py).then_some(a * 3 + b)
}
fn part1(input: &Input) -> i64 {
input.iter().copied().flat_map(solve).sum()
}
fn part2(input: &Input) -> i64 {
input
.iter()
.flat_map(
|&m @ Machine {
prize: (px, py), ..
}| {
solve(Machine {
prize: (px + 10000000000000, py + 10000000000000),
..m
})
},
)
.sum()
}
aoc::main!(2024, 13, ex: 1);