use std::env; use std::error::Error; use std::fs::File; use std::io::{BufReader, prelude::*}; fn parse_line(line: &str) -> Result<(i64, i64), Box> { // Split line on whitespace // Expecting "88789 64926" // Should end up with two string, if not something is wrong. let split_line: Vec<_> = line .splitn(2, char::is_whitespace) .map(|elm| elm.trim()) .collect(); // Parse and return our two elements let first_element = split_line[0].parse::()?; let second_element = split_line[1].parse::()?; 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, mut right_list: Vec) -> 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> { // Handle command input let args: Vec = env::args().collect(); if args.len() != 2 { panic!( "{} must be run with a single argument of files name!", &args[0] ) } let input_file_string = &args[1]; let input_file = File::open(input_file_string)?; let input_reader = BufReader::new(input_file); let mut left_list: Vec = Vec::new(); let mut right_list: Vec = Vec::new(); for line in input_reader.lines() { let line = line?; let parsed_line = parse_line(&line)?; //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(()); }