From 90edac903a4c0242e2e750ba978b31c50e7e9fe0 Mon Sep 17 00:00:00 2001 From: Logan G Date: Sat, 30 Nov 2024 23:56:32 -0700 Subject: [PATCH] Day 1 Part 2 --- day1/answer2 | 1 + day1/p2.rs | 86 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 87 insertions(+) create mode 100644 day1/answer2 create mode 100644 day1/p2.rs diff --git a/day1/answer2 b/day1/answer2 new file mode 100644 index 0000000..ded6afb --- /dev/null +++ b/day1/answer2 @@ -0,0 +1 @@ +24869388 diff --git a/day1/p2.rs b/day1/p2.rs new file mode 100644 index 0000000..0005341 --- /dev/null +++ b/day1/p2.rs @@ -0,0 +1,86 @@ +use std::env; +use std::fs; +use std::process; +use std::{thread, time}; +use std::collections::HashMap; + +fn main() { + //println!("Hello world!"); + + let args: Vec = env::args().collect(); + let mut path = String::from(""); + + 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 = vec![]; + let mut right: Vec = 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(); + + let mut leftDup = HashMap::new(); + let mut rightDup = HashMap::new(); + + // This is kinda ass but I don't care :) + let mut i: usize = 0; + while i < left.len() { + let mut k: usize = i; + while k < left.len() && left[i] == left[k] { + k+=1; + } + + leftDup.insert(left[i],k-i); + + i = k; + } + + //println!("{}", leftDup[&3]); + + i = 0; + while i < right.len() { + let mut k: usize = i; + while k < right.len() && right[i] == right[k] { + k+=1; + } + + rightDup.insert(right[i],k-i); + + i = k; + } + + //println!("{}", rightDup[&3]); + + let mut accum: i32 = 0; + for (left, num) in &leftDup { + let shit = match rightDup.get(left) { + Some(val) => *val, + None => 0, + }; + accum += (*left * (*num as i32)) * (shit as i32); + } + + println!("{}", accum); +}