logan_2024/day1/p2.rs

70 lines
1.6 KiB
Rust
Raw Normal View History

2024-12-01 01:56:32 -05:00
use std::env;
use std::fs;
use std::process;
2024-12-01 02:03:27 -05:00
//use std::{thread, time};
2024-12-01 01:56:32 -05:00
use std::collections::HashMap;
fn main() {
//println!("Hello world!");
let args: Vec<String> = env::args().collect();
2024-12-01 02:03:27 -05:00
let path: String;
2024-12-01 01:56:32 -05:00
if args.len() > 1 {
path = args[1].clone();
} else {
println!("Specify an input file!");
process::exit(1);
}
if ! fs::metadata(path.clone()).is_ok() {
println!("Path does not exist!");
process::exit(1);
}
//let rawInput = fs::read_to_string(path.clone()).unwrap();
//let splitInput: Vec<&str> = rawInput.lines().collect();
let mut left: Vec<i32> = vec![];
let mut right: Vec<i32> = vec![];
for line in fs::read_to_string(path.clone()).unwrap().lines() {
//let line = splitInput[i];
let split: Vec<&str> = line.split(" ").collect();
//println!("{}",split[0]);
left.push(split[0].parse().unwrap());
right.push(split[1].parse().unwrap());
}
left.sort();
right.sort();
2024-12-01 02:03:27 -05:00
let mut right_dup = HashMap::new();
2024-12-01 01:56:32 -05:00
2024-12-01 02:11:56 -05:00
// This is still kinda ass but I don't care :)
2024-12-01 01:56:32 -05:00
let mut i: usize = 0;
while i < right.len() {
let mut k: usize = i;
while k < right.len() && right[i] == right[k] {
k+=1;
}
2024-12-01 02:03:27 -05:00
right_dup.insert(right[i],k-i);
2024-12-01 01:56:32 -05:00
i = k;
}
let mut accum: i32 = 0;
2024-12-01 02:11:56 -05:00
for num in left {
let shit = match right_dup.get(&num) {
2024-12-01 01:56:32 -05:00
Some(val) => *val,
None => 0,
};
2024-12-01 02:11:56 -05:00
accum += num * (shit as i32);
2024-12-01 01:56:32 -05:00
}
2024-12-01 02:03:27 -05:00
println!("Answer: {}", accum);
2024-12-01 01:56:32 -05:00
}