2020: day13: part 1
This commit is contained in:
parent
bae2c9cb2c
commit
39d7098f36
6 changed files with 73 additions and 0 deletions
64
aoc2020/src/day13.rs
Normal file
64
aoc2020/src/day13.rs
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
use std::fmt::Write;
|
||||
|
||||
use aoc::err;
|
||||
|
||||
const INPUT: &str = include_str!("../input/day13.txt");
|
||||
|
||||
pub fn run() -> aoc::Result<String> {
|
||||
let mut res = String::with_capacity(128);
|
||||
|
||||
writeln!(res, "part 1: {}", part1(INPUT)?)?;
|
||||
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
fn part1(input: &str) -> aoc::Result<u64> {
|
||||
let mut lines = input.lines();
|
||||
|
||||
let earliest_timestamp = lines
|
||||
.next()
|
||||
.ok_or_else(|| err!("input was empty"))?
|
||||
.parse::<u64>()
|
||||
.map_err(|e| err!("couldn't parse first line: {}", e))?;
|
||||
|
||||
let bus_ids = lines
|
||||
.next()
|
||||
.ok_or_else(|| err!("no second line"))?
|
||||
.split(',')
|
||||
.filter_map(|num| {
|
||||
if num == "x" {
|
||||
None
|
||||
} else {
|
||||
Some(num.parse::<u64>().map_err(|e| err!("{}", e)))
|
||||
}
|
||||
})
|
||||
.collect::<aoc::Result<Vec<_>>>()?;
|
||||
|
||||
let (bus_id, earliest_departure) = bus_ids
|
||||
.iter()
|
||||
.map(|id| {
|
||||
let next_departure = ((earliest_timestamp / id) * id) + id;
|
||||
(id, next_departure)
|
||||
})
|
||||
.min_by_key(|(_, next_departure)| *next_departure)
|
||||
.unwrap();
|
||||
|
||||
Ok(bus_id * (earliest_departure - earliest_timestamp))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const PROVIDED: &str = include_str!("../input/day13_provided.txt");
|
||||
|
||||
#[test]
|
||||
fn part1_provided() {
|
||||
assert_eq!(part1(PROVIDED).unwrap(), 295);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part1_real() {
|
||||
assert_eq!(part1(INPUT).unwrap(), 3269);
|
||||
}
|
||||
}
|
||||
|
|
@ -10,3 +10,4 @@ pub mod day09;
|
|||
pub mod day10;
|
||||
pub mod day11;
|
||||
pub mod day12;
|
||||
pub mod day13;
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ use aoc2020::day09;
|
|||
use aoc2020::day10;
|
||||
use aoc2020::day11;
|
||||
use aoc2020::day12;
|
||||
use aoc2020::day13;
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let days: &[DayFunc] = &[
|
||||
|
|
@ -28,6 +29,7 @@ fn main() -> Result<()> {
|
|||
day10::run,
|
||||
day11::run,
|
||||
day12::run,
|
||||
day13::run,
|
||||
];
|
||||
|
||||
aoc::run(days)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue