This commit is contained in:
2024-12-03 23:31:21 +01:00
parent fb4cf8e8c0
commit 928218226b
7 changed files with 98 additions and 0 deletions

1
day-01-rust/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
target/

7
day-01-rust/Cargo.lock generated Normal file
View File

@@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "day-01-rust"
version = "0.1.0"

6
day-01-rust/Cargo.toml Normal file
View File

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

24
day-01-rust/src/main.rs Normal file
View File

@@ -0,0 +1,24 @@
mod task1;
mod task2;
fn main() {
let args = std::env::args().collect::<Vec<_>>();
if args.len() != 3 {
println!("Usage: {} <1|2> <input file>", args[0]);
return;
}
let task = args.get(1).unwrap();
match task.as_str() {
"1" => {
task1::run(&*read_input(args.get(2).unwrap()));
}
"2" => {
task2::run(&*read_input(args.get(2).unwrap()));
}
_ => { eprintln!("First argument has to be 1 or 2") }
}
}
fn read_input(file: &str) -> String {
std::fs::read_to_string(file).expect("Could not read file")
}

27
day-01-rust/src/task1.rs Normal file
View File

@@ -0,0 +1,27 @@
use std::str::FromStr;
pub fn run(input: &str) {
let mut first = Vec::<i64>::new();
let mut second = Vec::<i64>::new();
for line in input.split('\n') {
if let Some((first_part, second_part)) = line.split_once(" ") {
match i64::from_str(first_part) {
Ok(n) => first.push(n),
Err(err) => {
eprintln!("Failed to parse first number from {}: {}", first_part, err);
}
}
match i64::from_str(second_part) {
Ok(n) => second.push(n),
Err(err) => {
eprintln!("Failed to parse second number from {}: {}", second_part, err);
}
}
}
}
first.sort();
second.sort();
let sum = first.iter().zip(second.iter()).map(|(a, b)| a.abs_diff(*b)).sum::<u64>();
println!("Total difference: {}", sum);
}

31
day-01-rust/src/task2.rs Normal file
View File

@@ -0,0 +1,31 @@
use std::collections::HashMap;
use std::str::FromStr;
pub fn run(input: &str) {
let mut first = Vec::<i64>::new();
let mut second = Vec::<i64>::new();
for line in input.split('\n') {
if let Some((first_part, second_part)) = line.split_once(" ") {
match i64::from_str(first_part) {
Ok(n) => first.push(n),
Err(err) => {
eprintln!("Failed to parse first number from {}: {}", first_part, err);
}
}
match i64::from_str(second_part) {
Ok(n) => second.push(n),
Err(err) => {
eprintln!("Failed to parse second number from {}: {}", second_part, err);
}
}
}
}
let mut second_counts = HashMap::<i64, i64>::new();
for element in second {
*second_counts.entry(element).or_insert(0) += 1;
}
let result = first.iter().map(|num| num * second_counts.get(num).unwrap_or(&0)).sum::<i64>();
println!("Similarity: {}", result);
}