Part 1 complete

This commit is contained in:
2025-05-25 12:32:05 -05:00
parent 8ab8a09e8c
commit f836de316b

View File

@@ -1,7 +1,7 @@
use std::env;
use std::error::Error;
use std::fs::File;
use std::io::{self, BufReader, prelude::*};
use std::{env, fs};
use std::io::{BufReader, prelude::*};
fn parse_line(line: &str) -> Result<(i64, i64), Box<dyn Error>> {
// Split line on whitespace
@@ -18,6 +18,23 @@ fn parse_line(line: &str) -> Result<(i64, i64), Box<dyn Error>> {
return Ok((first_element, second_element));
}
/// Part one of day 1
/// Calculate the difference after sorting each list from smallest to biggest
fn calculate_diff(mut left_list: Vec<i64>, mut right_list: Vec<i64>) -> i64 {
// sort lists
left_list.sort();
right_list.sort();
let mut accumulator = 0;
for (index, left_value) in left_list.iter().enumerate() {
let right_value = right_list[index];
let absolute_diff = (left_value - right_value).abs();
accumulator += absolute_diff;
}
accumulator
}
fn main() -> Result<(), Box<dyn Error>> {
// Handle command input
let args: Vec<String> = env::args().collect();
@@ -32,11 +49,18 @@ fn main() -> Result<(), Box<dyn Error>> {
let input_file = File::open(input_file_string)?;
let input_reader = BufReader::new(input_file);
for (index, line) in input_reader.lines().enumerate() {
let mut left_list: Vec<i64> = Vec::new();
let mut right_list: Vec<i64> = Vec::new();
for line in input_reader.lines() {
let line = line?;
let parsed_line = parse_line(&line)?;
println!("({},{})", parsed_line.0, parsed_line.1);
//println!("({},{})", parsed_line.0, parsed_line.1);
left_list.push(parsed_line.0);
right_list.push(parsed_line.1);
}
println!("Result: {}", calculate_diff(left_list, right_list));
return Ok(());
}