49 lines
1.2 KiB
Rust
49 lines
1.2 KiB
Rust
//! Day 15 of 2020.
|
|
|
|
use crate::prelude::*;
|
|
|
|
/// Get the solution for day 15 of 2020.
|
|
pub fn solution() -> Solution {
|
|
Solution::new(Day::new(15, 2020), part_1, part_2).with_expected(441, 10613991)
|
|
}
|
|
|
|
/// Solve the puzzle for a given target.
|
|
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
|
|
}
|
|
|
|
/// The logic to solve part one.
|
|
fn part_1(input: &str) -> Result<String> {
|
|
Ok(solve(input, 2020).to_string())
|
|
}
|
|
|
|
/// The logic to solve part two.
|
|
fn part_2(input: &str) -> Result<String> {
|
|
Ok(solve(input, 30000000).to_string())
|
|
}
|