day13
This commit is contained in:
parent
c88b97182d
commit
9fc94b0e06
76
src/day13.rs
Normal file
76
src/day13.rs
Normal 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 (index, bus) in input.iter().enumerate() {
|
||||
if let Some(bus) = bus {
|
||||
while (min_value + index as i64) % bus != 0 {
|
||||
min_value += running_product;
|
||||
}
|
||||
running_product *= bus;
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
@ -1,3 +1,4 @@
|
||||
mod day13;
|
||||
mod day12;
|
||||
mod day10;
|
||||
mod day9;
|
||||
|
Loading…
Reference in New Issue
Block a user