-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday13.rs
110 lines (92 loc) · 2.49 KB
/
day13.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
//! [Day 13: Claw Contraption](https://adventofcode.com/2024/day/13)
use regex::Regex;
type F = fraction::GenericFraction<i64>;
struct ClawMachine {
a_x: F,
a_y: F,
b_x: F,
b_y: F,
p_x: F,
p_y: F,
}
impl ClawMachine {
fn parse(s: &str) -> Self {
let re = Regex::new(r"\d+").unwrap();
let values = re
.find_iter(s)
.map(|m| m.as_str().parse::<i64>().unwrap())
.collect::<Vec<_>>();
Self {
a_x: F::from(values[0]),
a_y: F::from(values[1]),
b_x: F::from(values[2]),
b_y: F::from(values[3]),
p_x: F::from(values[4]),
p_y: F::from(values[5]),
}
}
fn price(&self, position_offset: i64) -> i64 {
let p_x = self.p_x + position_offset;
let p_y = self.p_y + position_offset;
let a = (p_y - self.b_y * p_x / self.b_x) / (self.a_y - self.b_y * self.a_x / self.b_x);
let b = (p_x - a * self.a_x) / self.b_x;
if a.denom() != Some(&1) || a.is_sign_negative() {
return 0;
}
if b.denom() != Some(&1) || b.is_sign_negative() {
return 0;
}
*(a * 3 + b).numer().unwrap()
}
}
struct Puzzle {
machines: Vec<ClawMachine>,
}
impl Puzzle {
const fn new() -> Self {
Self { machines: vec![] }
}
/// Get the puzzle input.
fn configure(&mut self, data: &str) {
for s in data.split("\n\n") {
self.machines.push(ClawMachine::parse(s));
}
}
/// Solve part one.
fn part1(&self) -> i64 {
self.machines.iter().map(|machine| machine.price(0)).sum()
}
/// Solve part two.
fn part2(&self) -> i64 {
self.machines
.iter()
.map(|machine| machine.price(10_000_000_000_000))
.sum()
}
}
fn main() {
let args = aoc::parse_args();
let mut puzzle = Puzzle::new();
puzzle.configure(&args.input);
println!("{}", puzzle.part1());
println!("{}", puzzle.part2());
}
/// Test from puzzle input
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test01() {
let mut puzzle = Puzzle::new();
let data = aoc::load_input_data("test.txt");
puzzle.configure(&data);
assert_eq!(puzzle.part1(), 480);
}
#[test]
fn test02() {
let mut puzzle = Puzzle::new();
let data = aoc::load_input_data("test.txt");
puzzle.configure(&data);
assert_eq!(puzzle.part2(), 875318608908);
}
}