From d85a0511dc5720824fcb05c94df02ec5fd769aa5 Mon Sep 17 00:00:00 2001 From: kleph Date: Mon, 2 Dec 2024 01:04:46 +0100 Subject: [PATCH] 2024 - Day 1 part 2 - rust --- 2024/rust1_2/.gitignore | 2 ++ 2024/rust1_2/Cargo.toml | 6 ++++++ 2024/rust1_2/src/main.rs | 34 ++++++++++++++++++++++++++++++++++ 3 files changed, 42 insertions(+) create mode 100644 2024/rust1_2/.gitignore create mode 100644 2024/rust1_2/Cargo.toml create mode 100644 2024/rust1_2/src/main.rs diff --git a/2024/rust1_2/.gitignore b/2024/rust1_2/.gitignore new file mode 100644 index 0000000..a9d37c5 --- /dev/null +++ b/2024/rust1_2/.gitignore @@ -0,0 +1,2 @@ +target +Cargo.lock diff --git a/2024/rust1_2/Cargo.toml b/2024/rust1_2/Cargo.toml new file mode 100644 index 0000000..d940546 --- /dev/null +++ b/2024/rust1_2/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "rust1_2" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/2024/rust1_2/src/main.rs b/2024/rust1_2/src/main.rs new file mode 100644 index 0000000..ff49d23 --- /dev/null +++ b/2024/rust1_2/src/main.rs @@ -0,0 +1,34 @@ +use std::io::{BufRead, BufReader}; +use std::fs::File; +use std::collections::HashMap; + +fn main (){ + // let filename = "../1/input_example.txt"; + let filename = "../1/input.txt"; + let file = BufReader::new(File::open(filename).expect("Unable to open file")); + let mut accum: u32 = 0; + + let mut list1: Vec = vec![]; + let mut counters: HashMap = HashMap::new(); + + for line in file.lines() { + let wline = line.unwrap(); + let nums: Vec<&str> = wline.split(' ') + .filter(|&x| !x.is_empty()) + .collect(); + + list1.push(nums[0].parse().unwrap()); + + counters.entry(nums[1].parse().unwrap()) + .and_modify(|e| {*e += 1}) + .or_insert(1); + } + + for n in list1 { + if counters.contains_key(&n){ + accum += n * counters[&n]; + } + } + + println!("{}", accum); +}