diff --git a/day-05/Cargo.lock b/day-05/Cargo.lock new file mode 100644 index 0000000..992643d --- /dev/null +++ b/day-05/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "day-05" +version = "0.1.0" diff --git a/day-05/Cargo.toml b/day-05/Cargo.toml new file mode 100644 index 0000000..ac394aa --- /dev/null +++ b/day-05/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "day-05" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/day-05/src/main.rs b/day-05/src/main.rs new file mode 100644 index 0000000..29147b4 --- /dev/null +++ b/day-05/src/main.rs @@ -0,0 +1,79 @@ +const INPUT: &str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/input.txt")); + +fn main() { + let mut deps = [[false; 100]; 100]; + + let mut lines = INPUT.lines(); + while let Some(line) = lines.next() { + if line.is_empty() { break } + let (first, second) = line.split_at(line.find("|").unwrap()); + let first = str::parse::(first).unwrap(); + let second = str::parse::(second.trim().trim_start_matches('|')).unwrap(); + + deps[first as usize][second as usize] = true; + } + + + let sequences = lines.map(|line| { + line.split_terminator(",") + .map(|num| { + str::parse::(num).unwrap() + }) + }); + + { + let mut sequences = sequences.clone(); + + let mut total = 0; + while let Some(line) = sequences.next() { + let numbers: Vec<_> = line.collect(); + + if ordered(deps, &numbers[..]) { + total += u32::from(numbers[numbers.len() / 2]); + } + } + + println!("Part 1: {}", total); + } + + { + let mut sequences = sequences.clone(); + + let mut total = 0; + while let Some(line) = sequences.next() { + let mut numbers: Vec<_> = line.collect(); + + if !ordered(deps, &numbers[..]) { + order(deps, &mut numbers); + total += u32::from(numbers[numbers.len() / 2]); + } + } + + println!("Part 2: {}", total); + } +} + +fn ordered(graph: [[bool; 100]; 100], list: &[u8]) -> bool { + for i in 0..list.len() { + for j in (i + 1)..list.len() { + if graph[list[j] as usize][list[i] as usize] { + return false + } + } + } + true +} + +fn order(graph: [[bool; 100]; 100], list: &mut Vec) { + use std::cmp::Ordering; + list.sort_by(|&first, &second| { + if graph[first as usize][second as usize] { + Ordering::Less + } else if graph[second as usize][first as usize] { + Ordering::Greater + } else { + Ordering::Equal + } + }) +} +