-
Notifications
You must be signed in to change notification settings - Fork 0
/
day_14.rs
92 lines (85 loc) · 2.96 KB
/
day_14.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
//! https://adventofcode.com/2018/day/14
//! https://adventofcode.com/2018/day/14/input
use std::{fs::read_to_string, time::Instant};
fn parse(input: &str) -> usize {
input.parse().unwrap()
}
pub mod part1 {
use super::parse;
pub fn solve(input: &str) -> String {
let target = parse(input) + 10;
let mut recipes = vec![3, 7];
let (mut first, mut second) = (0, 1);
while recipes.len() <= target {
let sum = recipes[first] + recipes[second];
if sum >= 10 {
recipes.push(sum / 10);
}
recipes.push(sum % 10);
first = (first + recipes[first] + 1) % recipes.len();
second = (second + recipes[second] + 1) % recipes.len();
}
recipes
.iter()
.skip(target - 10)
.take(10)
.map(|recipe| (*recipe as u8 + b'0') as char)
.collect()
}
}
pub mod part2 {
use std::collections::VecDeque;
pub fn solve(input: &str) -> usize {
let target = VecDeque::from_iter(input.chars().map(|char| (char as u8 - b'0') as usize));
let mut recipes = vec![3, 7];
let (mut first, mut second) = (0, 1);
while recipes.len() <= target.len() {
let sum = recipes[first] + recipes[second];
if sum >= 10 {
recipes.push(sum / 10);
}
recipes.push(sum % 10);
first = (first + recipes[first] + 1) % recipes.len();
second = (second + recipes[second] + 1) % recipes.len();
}
let mut current = VecDeque::with_capacity(target.len());
for recipe in recipes.iter().take(target.len()) {
current.push_back(*recipe);
}
let mut next_recipe = current.len();
let offset = recipes.len() - current.len();
while current != target {
let sum = recipes[first] + recipes[second];
if sum >= 10 {
current.pop_front();
recipes.push(sum / 10);
current.push_back(recipes[next_recipe]);
next_recipe += 1;
}
if current == target {
break;
}
current.pop_front();
recipes.push(sum % 10);
current.push_back(recipes[next_recipe]);
next_recipe += 1;
first = (first + recipes[first] + 1) % recipes.len();
second = (second + recipes[second] + 1) % recipes.len();
}
recipes.len() - target.len() - offset
}
}
pub fn main(test: bool) {
let test_input = "59414".to_owned();
let puzzle_input = if test {
test_input
} else {
read_to_string("../inputs/2018/day_14_input.txt").unwrap()
};
let start = Instant::now();
println!("{}", part1::solve(&puzzle_input));
println!("Run in {:?}", start.elapsed());
let start = Instant::now();
println!("{}", part2::solve(&puzzle_input));
println!("Run in {:?}", start.elapsed());
}