|
| 1 | +// ╭─────────────────────────────────────────────────────────╮ |
| 2 | +// │ Advent of Code 2024 - Day 5 │ |
| 3 | +// ╰─────────────────────────────────────────────────────────╯ |
| 4 | + |
| 5 | +use std::cmp::Ordering; |
| 6 | + |
| 7 | +fn main() { |
| 8 | + let (unparsed_rules, unparsed_updates) = include_str!("../input.txt").split_once("\n\n").expect("Invalid input"); |
| 9 | + let rules = unparsed_rules.lines() |
| 10 | + .map(|line| line.split_once("|").unwrap()) |
| 11 | + .map(|(a, b)| (a.parse::<u32>().unwrap(), b.parse::<u32>().unwrap())) |
| 12 | + .collect::<Vec<_>>(); |
| 13 | + let updates = unparsed_updates.lines() |
| 14 | + .map(|line| line.split(",").map(|page| page.parse::<u32>().unwrap()).collect::<Vec<_>>()) |
| 15 | + .collect::<Vec<_>>(); |
| 16 | + // ── Part 1 ────────────────────────────────────────────────────────── |
| 17 | + let result_part1 = updates.iter() |
| 18 | + .filter(|update| rules.iter().all(|rule| complies_with_rule(rule, update))) |
| 19 | + .map(|update| update[update.len() / 2]) |
| 20 | + .sum::<u32>(); |
| 21 | + |
| 22 | + println!("Result: {}", result_part1); |
| 23 | + // ── Part 2 ────────────────────────────────────────────────────────── |
| 24 | + let result_part2 = updates.iter() |
| 25 | + .filter(|update| !rules.iter().all(|rule| complies_with_rule(rule, update))) |
| 26 | + .map(|update| { |
| 27 | + let mut sorted_update = update.clone(); |
| 28 | + sorted_update.sort_unstable_by(|a, b| { |
| 29 | + match rules.iter().find(|&(x, y)| (x == a || x == b) && (y == a || y == b)) { |
| 30 | + Some((x, y)) => { |
| 31 | + if a == x && b == y { Ordering::Less } |
| 32 | + else { Ordering::Greater } |
| 33 | + }, |
| 34 | + None => Ordering::Equal |
| 35 | + } |
| 36 | + }); |
| 37 | + sorted_update |
| 38 | + }) |
| 39 | + .map(|update| update[update.len() / 2]) |
| 40 | + .sum::<u32>(); |
| 41 | + println!("Result: {}", result_part2); |
| 42 | +} |
| 43 | + |
| 44 | +fn complies_with_rule(rule: &(u32, u32), update: &Vec<u32>) -> bool { |
| 45 | + let (a, b) = rule; |
| 46 | + |
| 47 | + !update.contains(&a) |
| 48 | + || !update.contains(&b) |
| 49 | + || update.iter().position(|page| page == a).unwrap() < update.iter().position(|page| page == b).unwrap() |
| 50 | +} |
0 commit comments