From de9b94c9a6fb7b0fdb52e1253debb633af417c66 Mon Sep 17 00:00:00 2001 From: Antoine Martin Date: Sat, 5 Dec 2020 10:52:30 +0100 Subject: [PATCH] 2020: day05: part 2 --- aoc2020/src/day05.rs | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/aoc2020/src/day05.rs b/aoc2020/src/day05.rs index 93ccbb9..4cf1866 100644 --- a/aoc2020/src/day05.rs +++ b/aoc2020/src/day05.rs @@ -9,6 +9,7 @@ pub fn run() -> aoc::Result { let mut res = String::with_capacity(128); writeln!(res, "part 1: {}", part1(INPUT)?)?; + writeln!(res, "part 2: {}", part2(INPUT)?)?; Ok(res) } @@ -27,7 +28,31 @@ fn part1(input: &str) -> aoc::Result { .ok_or_else(|| err!("0 seats processed")) } -#[derive(Debug, PartialEq, Eq)] +fn part2(input: &str) -> aoc::Result { + let mut seats = input + .lines() + .map(|line| line.parse()) + .collect::>>() + .map_err(|e| err!("{}", e))?; + + // Seats will be sorted by lexicographical order of fields thanks to `derive(PartialOrd, Ord)`, + // which should produce the same result as a manual implementation of `Ord` and `PartialOrd` + // using the `id()` method. + seats.sort_unstable(); + + let mut prev_id = None; + for id in seats.iter().map(|s| s.id()) { + match prev_id { + Some(pid) if pid == (id - 1) => prev_id = Some(id), + Some(pid) => return Ok(pid + 1), + None => prev_id = Some(id), + } + } + + Err(err!("didn't find missing seat")) +} + +#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)] struct Seat { row: usize, column: usize, @@ -105,4 +130,9 @@ mod tests { fn part1_real() { assert_eq!(part1(INPUT).unwrap(), 850); } + + #[test] + fn part2_real() { + assert_eq!(part2(INPUT).unwrap(), 599); + } }