2024 - Day 1 part 2 - rust

This commit is contained in:
kleph 2024-12-02 01:04:46 +01:00
parent 8ce7e826bf
commit d85a0511dc
3 changed files with 42 additions and 0 deletions

2
2024/rust1_2/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
target
Cargo.lock

6
2024/rust1_2/Cargo.toml Normal file
View file

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

34
2024/rust1_2/src/main.rs Normal file
View file

@ -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<u32> = vec![];
let mut counters: HashMap<u32, u32> = 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);
}