From bf4be8d233ccd0b79be21cc26295cff1b83f8038 Mon Sep 17 00:00:00 2001 From: Tobias Marschner Date: Sun, 11 Feb 2024 04:43:54 +0100 Subject: [PATCH] Solution for 2022/day03-part2 --- 2022/day03-part2/Cargo.toml | 8 ++++++++ 2022/day03-part2/src/main.rs | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 2022/day03-part2/Cargo.toml create mode 100644 2022/day03-part2/src/main.rs diff --git a/2022/day03-part2/Cargo.toml b/2022/day03-part2/Cargo.toml new file mode 100644 index 0000000..d0ac9ff --- /dev/null +++ b/2022/day03-part2/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "day03-part2" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/2022/day03-part2/src/main.rs b/2022/day03-part2/src/main.rs new file mode 100644 index 0000000..f86a5d1 --- /dev/null +++ b/2022/day03-part2/src/main.rs @@ -0,0 +1,35 @@ +use std::collections::HashSet; + +fn main() { + // Use command line arguments to specify the input filename. + let args: Vec = std::env::args().collect(); + if args.len() < 2 { + panic!("Usage: ./main \nNo input file provided. Exiting."); + } + + // Next, read the contents of the input file into a string for easier processing. + let input = std::fs::read_to_string(&args[1]).expect("Error opening file"); + // Line-by-line processing is easiest. + let mut input = input.lines(); + + // --- TASK BEGIN --- + let mut total = 0; + while let Some(line) = input.next() { + // Read the next three lines and turn them into HashSets. + let first: HashSet = line.chars().collect(); + let second: HashSet = input.next().unwrap().chars().collect(); + let third: HashSet = input.next().unwrap().chars().collect(); + // Use set intersection to determine the item that's common to all three sets. + let item = *first.intersection(&second).copied().collect::>().intersection(&third).next().unwrap(); + // Calculate the priority. + let priority = match item { + item if item.is_ascii_lowercase() => (item as u32) - ('a' as u32) + 1, + item if item.is_ascii_uppercase() => (item as u32) - ('A' as u32) + 27, + _ => {panic!("Character out of range")} + }; + // Accumulate the priorities. + total += priority; + } + println!("Total priority: {total}"); +} +