This commit is contained in:
Andrew Glaze 2023-12-28 16:35:19 -05:00
parent c88b97182d
commit a7ea07a089
2 changed files with 77 additions and 0 deletions

76
src/day13.rs Normal file
View File

@ -0,0 +1,76 @@
use aoc_runner_derive::{aoc, aoc_generator};
use itertools::Itertools;
#[aoc_generator(day13, part1)]
fn parse(input: &str) -> (i32, Vec<i32>) {
let (start, buses) = input
.lines()
.collect_tuple()
.unwrap();
let buses = buses
.split(',')
.filter_map(|num| num.parse::<i32>().ok())
.collect_vec();
(start.parse::<i32>().unwrap(), buses)
}
#[aoc(day13, part1)]
fn part1((start, buses): &(i32, Vec<i32>)) -> i32 {
let mut cur = 0;
loop {
if let Some(bus) = buses.iter().find(|x| (cur + start) % *x == 0) {
return bus * cur;
}
cur += 1;
}
}
#[aoc_generator(day13, part2)]
fn parse2(input: &str) -> Vec<Option<i64>> {
let buses = input
.lines().skip(1).next().unwrap();
let buses = buses
.split(',')
.map(|num| num.parse::<i64>().ok())
.collect_vec();
buses
}
#[aoc(day13, part2)]
fn part2(input: &Vec<Option<i64>>) -> i64 {
let mut min_value = 0;
let mut running_product = 1;
for (v, k) in input.iter().enumerate() {
if let Some(k) = k {
while (min_value + v as i64) % k != 0 {
min_value += running_product;
}
running_product *= k;
}
}
min_value
}
#[cfg(test)]
mod tests {
use super::*;
const EX: &str = r"939
7,13,x,x,59,x,31,19";
#[test]
fn part1_example() {
assert_eq!(part1(&parse(EX)), 295);
}
#[test]
fn part2_example() {
assert_eq!(part2(&parse2(EX)), 1068781);
}
}

View File

@ -1,3 +1,4 @@
mod day13;
mod day12;
mod day10;
mod day9;