|
| 1 | +//! # Print Queue |
| 2 | +//! |
| 3 | +//! Numbers are always 2 digits so storing directed edges in a fixed size 100 x 100 array is much |
| 4 | +//! faster than using a `HashMap`. |
| 5 | +//! |
| 6 | +//! The ordering graph has cycles so we can't use a |
| 7 | +//! [topological sort](https://en.wikipedia.org/wiki/Topological_sorting). |
| 8 | +//! A simple `O(n²)` [selection sort](https://en.wikipedia.org/wiki/Selection_sort) works well as |
| 9 | +//! the length of each updates is reasonably short. |
| 10 | +use crate::util::iter::*; |
| 11 | +use crate::util::parse::*; |
| 12 | + |
| 13 | +type Input = (usize, usize); |
| 14 | + |
| 15 | +pub fn parse(input: &str) -> Input { |
| 16 | + let (prefix, suffix) = input.split_once("\n\n").unwrap(); |
| 17 | + let mut after = [[true; 100]; 100]; |
| 18 | + |
| 19 | + for [from, to] in prefix.iter_unsigned::<usize>().chunk::<2>() { |
| 20 | + after[to][from] = false; |
| 21 | + } |
| 22 | + |
| 23 | + let mut todo = Vec::new(); |
| 24 | + let mut part_one = 0; |
| 25 | + let mut part_two = 0; |
| 26 | + |
| 27 | + for line in suffix.lines() { |
| 28 | + let mut ordered = true; |
| 29 | + |
| 30 | + todo.clear(); |
| 31 | + todo.extend(line.iter_unsigned::<usize>()); |
| 32 | + |
| 33 | + // Sort updates into correct order. |
| 34 | + for current in 0..todo.len() { |
| 35 | + let offset = todo[current..] |
| 36 | + .iter() |
| 37 | + .enumerate() |
| 38 | + .position(|(i, &from)| todo[current + i + 1..].iter().all(|&to| after[from][to])) |
| 39 | + .unwrap(); |
| 40 | + |
| 41 | + let next = current + offset; |
| 42 | + todo.swap(current, next); |
| 43 | + ordered &= current == next; |
| 44 | + } |
| 45 | + |
| 46 | + if ordered { |
| 47 | + part_one += todo[todo.len() / 2]; |
| 48 | + } else { |
| 49 | + part_two += todo[todo.len() / 2]; |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + (part_one, part_two) |
| 54 | +} |
| 55 | + |
| 56 | +pub fn part1(input: &Input) -> usize { |
| 57 | + input.0 |
| 58 | +} |
| 59 | + |
| 60 | +pub fn part2(input: &Input) -> usize { |
| 61 | + input.1 |
| 62 | +} |
0 commit comments