This commit is contained in:
dobiadi
2024-12-05 13:55:17 +01:00
parent e00e7079db
commit 38560fc3bc
7 changed files with 1637 additions and 0 deletions

25
day5/rust/Cargo.lock generated Normal file
View File

@@ -0,0 +1,25 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "either"
version = "1.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0"
[[package]]
name = "itertools"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
dependencies = [
"either",
]
[[package]]
name = "rust"
version = "0.1.0"
dependencies = [
"itertools",
]

7
day5/rust/Cargo.toml Normal file
View File

@@ -0,0 +1,7 @@
[package]
name = "rust"
version = "0.1.0"
edition = "2021"
[dependencies]
itertools = "0.13.0"

74
day5/rust/src/main.rs Normal file
View File

@@ -0,0 +1,74 @@
use std::{cmp::Ordering, io::Read};
use itertools::Itertools;
struct Rule {
first: isize,
second: isize,
}
fn main() {
let mut stdin = std::io::stdin();
let mut input = String::new();
stdin.read_to_string(&mut input).unwrap();
let (rules_string, updates_string) = input.split("\n\n").collect_tuple().unwrap();
let rules: Vec<_> = rules_string
.split("\n")
.filter(|e| e.len() > 0)
.map(|e| {
e.split("|")
.map(|e| e.parse().unwrap())
.collect_tuple::<(isize, isize)>()
.unwrap()
})
.map(|e| Rule {
first: e.0,
second: e.1,
})
.collect();
let updates: Vec<_> = updates_string
.split("\n")
.filter(|e| e.len() > 0)
.map(|e| {
e.split(",")
.map(|e| e.parse().unwrap())
.collect::<Vec<isize>>()
})
.collect();
let mut count = 0;
let mut count2 = 0;
updates.iter().for_each(|update| {
let mut sorted = update.clone();
sorted.sort_by(|&a, &b| {
if let Some(_) = rules
.iter()
.find(|rule| rule.first == a && rule.second == b)
{
return Ordering::Less;
}
if let Some(_) = rules
.iter()
.find(|rule| rule.second == a && rule.first == b)
{
return Ordering::Greater;
}
return Ordering::Equal;
});
if sorted == *update {
count += update[update.len() / 2];
} else {
count2 += sorted[update.len() / 2];
}
});
println!("{}", count);
println!("{}", count2);
}