This commit is contained in:
cool-mist
2024-12-03 14:24:50 +05:30
commit 8ef11b2293
6 changed files with 1101 additions and 0 deletions
+63
View File
@@ -0,0 +1,63 @@
use std::collections::HashSet;
pub struct Day1 {
pub input: String,
}
impl Day1 {
pub fn new() -> Day1 {
let input = include_bytes!("input");
let input = String::from_utf8_lossy(input);
Day1 {
input: input.to_string(),
}
}
pub fn part_one(&self) {
let mut left: Vec<i32> = Vec::new();
let mut right: Vec<i32> = Vec::new();
self.input.lines().for_each(|line| {
let mut parts = line.split_whitespace();
left.push(parts.next().unwrap().parse().unwrap());
right.push(parts.next().unwrap().parse().unwrap());
});
left.sort();
right.sort();
let res = left
.iter()
.zip(right.iter())
.map(|(l, r)| Day1::abs(*l, *r))
.sum::<i32>();
println!("{}", res);
}
fn abs(a: i32, b: i32) -> i32 {
if a > b {
a - b
} else {
b - a
}
}
pub fn part_two(&self) {
let mut left: HashSet<i32> = HashSet::new();
let mut right: Vec<i32> = Vec::new();
self.input.lines().for_each(|line| {
let mut parts = line.split_whitespace();
left.insert(parts.next().unwrap().parse().unwrap());
right.push(parts.next().unwrap().parse().unwrap());
});
let mut acc = 0;
for r in right.iter() {
if left.contains(r) {
acc = acc + *r;
}
}
println!("{}", acc);
}
}