From 47eaa0bd32a64dcb48b58d6dcb3a0193738c6df7 Mon Sep 17 00:00:00 2001 From: Tobias Marschner Date: Sun, 11 Feb 2024 06:10:06 +0100 Subject: [PATCH] Solution for 2022/day04-part2 --- 2022/day04-part2/Cargo.toml | 8 +++++++ 2022/day04-part2/src/main.rs | 46 ++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 2022/day04-part2/Cargo.toml create mode 100644 2022/day04-part2/src/main.rs diff --git a/2022/day04-part2/Cargo.toml b/2022/day04-part2/Cargo.toml new file mode 100644 index 0000000..bf5fe6c --- /dev/null +++ b/2022/day04-part2/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "day04-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/day04-part2/src/main.rs b/2022/day04-part2/src/main.rs new file mode 100644 index 0000000..3d8a641 --- /dev/null +++ b/2022/day04-part2/src/main.rs @@ -0,0 +1,46 @@ +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 input = input.lines(); + + // --- TASK BEGIN --- + let mut count = 0; + + for line in input { + // Turn "1-2,3-6" into ["1-2", "3-6"]. + let ranges = line.split(',').collect::>(); + // Turn ["1-2", "3-6"] into [["1", "2"], ["3", "6"]] + let ranges = ranges + .iter() + .map(|x| x.split('-').collect::>()) + .collect::>(); + // Turn [["1", "2"], ["3", "6"]] into [1..=2, 3..=6] + let ranges = ranges + .iter() + .map(|x| (x[0].parse::().unwrap())..=(x[1].parse::().unwrap())) + .collect::>(); + // Now turn the ranges into HashSets containing the respective integers. Essentially: + // Turn [1..=2, 3..=6] into [{1,2}, {3,4,5,6}] + let sets = ranges + .into_iter() + .map(|x| x.collect::>()) + .collect::>(); + + // Check if the two sets are disjoint. + // If there's at least one overlapping element, add it to the count. + if !sets[0].is_disjoint(&sets[1]) { + count += 1; + } + } + + println!("Count: {}", count); +}