This commit is contained in:
Aaron Manning 2024-12-05 17:24:12 +11:00
parent 81a852e92e
commit 32712845e4
3 changed files with 92 additions and 0 deletions

7
day-05/Cargo.lock generated Normal file
View File

@ -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"

6
day-05/Cargo.toml Normal file
View File

@ -0,0 +1,6 @@
[package]
name = "day-05"
version = "0.1.0"
edition = "2021"
[dependencies]

79
day-05/src/main.rs Normal file
View File

@ -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::<u8>(first).unwrap();
let second = str::parse::<u8>(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::<u8>(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<u8>) {
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
}
})
}