mirror of
https://github.com/bertptrs/adventofcode.git
synced 2025-12-25 21:00:31 +01:00
Implementation day 13
This commit is contained in:
@@ -40,6 +40,21 @@ pub fn read_char_grid(input: &mut dyn Read) -> Vec<Vec<u8>> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn numbers_and_stuff<T, C>(input: &mut dyn Read) -> C
|
||||
where
|
||||
T: FromStr,
|
||||
C: FromIterator<T>,
|
||||
{
|
||||
let mut buffer = String::new();
|
||||
|
||||
input.read_to_string(&mut buffer).unwrap();
|
||||
|
||||
buffer
|
||||
.split(|c: char| !c.is_ascii_digit())
|
||||
.filter_map(|t| t.parse().ok())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// An interface to count elements in particular categories.
|
||||
pub trait GroupingCount {
|
||||
/// The type of the categories under inspection
|
||||
|
||||
@@ -1,12 +1,69 @@
|
||||
use std::io::Read;
|
||||
|
||||
use num_integer::Integer;
|
||||
|
||||
use crate::common::numbers_and_stuff;
|
||||
use crate::common::Lines;
|
||||
use crate::Solution;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Day13;
|
||||
|
||||
impl Solution for Day13 {
|
||||
fn part1(&mut self, _input: &mut dyn Read) -> String {
|
||||
todo!()
|
||||
fn part1(&mut self, input: &mut dyn Read) -> String {
|
||||
let numbers: Vec<u32> = numbers_and_stuff(input);
|
||||
|
||||
let departure = numbers[0];
|
||||
|
||||
let (wait, id) = numbers[1..]
|
||||
.iter()
|
||||
.map(|&interval| (interval - (departure % interval), interval))
|
||||
.min()
|
||||
.unwrap();
|
||||
|
||||
(wait * id).to_string()
|
||||
}
|
||||
|
||||
fn part2(&mut self, input: &mut dyn Read) -> String {
|
||||
let line = Lines::new(input).nth(1).unwrap();
|
||||
|
||||
let mut period = 1;
|
||||
let mut wait = 0;
|
||||
|
||||
for (offset, freq) in line
|
||||
.split(',')
|
||||
.enumerate()
|
||||
.filter_map(|(i, s)| s.parse().ok().map(|n| (i as u64, n)))
|
||||
{
|
||||
let offset = (freq - (offset % freq)) % freq;
|
||||
|
||||
// Modular integer division does this faster but this works.
|
||||
while wait % freq != offset {
|
||||
wait += period;
|
||||
}
|
||||
|
||||
period = period.lcm(&freq);
|
||||
}
|
||||
|
||||
wait.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::test_implementation;
|
||||
|
||||
use super::*;
|
||||
|
||||
const SAMPLE: &[u8] = include_bytes!("../samples/13.txt");
|
||||
|
||||
#[test]
|
||||
fn sample_part1() {
|
||||
test_implementation!(Day13, 1, SAMPLE, 295);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sample_part2() {
|
||||
test_implementation!(Day13, 2, SAMPLE, 1068781);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user