2024-01-14 21:04:10 +00:00
|
|
|
//! Day 15 of 2020.
|
|
|
|
|
2022-10-03 16:02:40 +00:00
|
|
|
use crate::prelude::*;
|
|
|
|
|
2024-01-14 21:04:10 +00:00
|
|
|
/// Get the solution for day 15 of 2020.
|
2022-10-03 16:02:40 +00:00
|
|
|
pub fn solution() -> Solution {
|
|
|
|
Solution::new(Day::new(15, 2020), part_1, part_2).with_expected(441, 10613991)
|
|
|
|
}
|
|
|
|
|
2024-01-14 21:04:10 +00:00
|
|
|
/// Solve the puzzle for a given target.
|
2022-10-03 16:02:40 +00:00
|
|
|
fn solve(input: &str, target: usize) -> isize {
|
|
|
|
let mut numbers = HashMap::new();
|
|
|
|
let mut previous_number = (0, (0, 0));
|
|
|
|
|
|
|
|
for (index, number) in input
|
|
|
|
.trim()
|
|
|
|
.split(',')
|
|
|
|
.map(str::parse::<isize>)
|
|
|
|
.map(Result::unwrap)
|
|
|
|
.enumerate()
|
|
|
|
{
|
|
|
|
numbers.insert(number, (index, index));
|
|
|
|
previous_number = (number, (index, index));
|
|
|
|
}
|
|
|
|
|
|
|
|
for index in numbers.len()..target {
|
|
|
|
let next_num = previous_number.1 .1 - previous_number.1 .0;
|
|
|
|
let num = numbers
|
|
|
|
.entry(next_num as isize)
|
|
|
|
.or_insert_with(|| (index, index));
|
|
|
|
num.0 = num.1;
|
|
|
|
num.1 = index;
|
|
|
|
|
|
|
|
previous_number = (next_num as isize, *num);
|
|
|
|
}
|
|
|
|
|
|
|
|
*numbers.iter().max_by(|a, b| a.1 .1.cmp(&b.1 .1)).unwrap().0
|
|
|
|
}
|
|
|
|
|
2024-01-14 21:04:10 +00:00
|
|
|
/// The logic to solve part one.
|
2022-10-03 16:02:40 +00:00
|
|
|
fn part_1(input: &str) -> Result<String> {
|
|
|
|
Ok(solve(input, 2020).to_string())
|
|
|
|
}
|
|
|
|
|
2024-01-14 21:04:10 +00:00
|
|
|
/// The logic to solve part two.
|
2022-10-03 16:02:40 +00:00
|
|
|
fn part_2(input: &str) -> Result<String> {
|
|
|
|
Ok(solve(input, 30000000).to_string())
|
|
|
|
}
|