-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution_2016_15.rs
88 lines (71 loc) · 1.85 KB
/
solution_2016_15.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
use advent_of_code_common::parsing::{Error, parse_lines_to_vec};
use recap::Recap;
use serde::Deserialize;
#[derive(Debug, Deserialize, Recap)]
#[recap(
regex = r#"^Disc #(?P<id>\d+) has (?P<positions>\d+) positions; at time=0, it is at position (?P<at_time_0>\d+).$"#
)]
struct Disc {
id: usize,
positions: usize,
at_time_0: usize,
}
impl Disc {
fn valid_at(&self, time: usize) -> bool {
let effective_time = self.id + time;
(self.at_time_0 + effective_time) % self.positions == 0
}
}
fn parse(input: &str) -> Result<Vec<Disc>, Error> {
parse_lines_to_vec(input)
}
fn is_valid(time: usize, data: &[Disc]) -> bool {
data.iter().all(|d| d.valid_at(time))
}
fn solve(data: &[Disc]) -> usize {
for i in 0 .. usize::MAX {
if is_valid(i, data) {
return i;
}
}
panic!("Failed to find")
}
fn part_1(input: &str) -> Result<usize, Error> {
parse(input).map(|x| solve(&x))
}
fn part_2(input: &str) -> Result<usize, Error> {
let mut discs = parse(input)?;
let extra_disc = Disc {
id: discs.len() + 1,
positions: 11,
at_time_0: 0,
};
discs.push(extra_disc);
let result = solve(&discs);
Ok(result)
}
const DATA: &str = include_str!("../../resources/15.txt");
fn main() -> Result<(), Error> {
let result_1 = part_1(DATA)?;
println!("Part 1: {result_1:?}");
let result_2 = part_2(DATA)?;
println!("Part 2: {result_2:?}");
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
const TEST: &str = include_str!("../../resources/15-test.txt");
#[test]
fn test_solve_1_test() {
assert_eq!(part_1(TEST), Ok(5));
}
#[test]
fn test_solve_1_real() {
assert_eq!(part_1(DATA), Ok(203_660));
}
#[test]
fn test_solve_2_real() {
assert_eq!(part_2(DATA), Ok(2_408_135));
}
}