Day 1 complete
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
use std::collections::HashMap;
|
||||
use std::env;
|
||||
use std::error::Error;
|
||||
use std::fs::File;
|
||||
@@ -18,8 +19,19 @@ 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
|
||||
/// Part 1
|
||||
///
|
||||
/// Maybe the lists are only off by a small amount! To find out, pair
|
||||
/// up the numbers and measure how far apart they are. Pair up the
|
||||
/// smallest number in the left list with the smallest number in the
|
||||
/// right list, then the second-smallest left number with the
|
||||
/// second-smallest right number, and so on.
|
||||
///
|
||||
/// Within each pair, figure out how far apart the two numbers are;
|
||||
/// you'll need to add up all of those distances. For example, if you
|
||||
/// pair up a 3 from the left list with a 7 from the right list, the
|
||||
/// distance apart is 4; if you pair up a 9 with a 3, the distance
|
||||
/// apart is 6.
|
||||
fn calculate_diff(mut left_list: Vec<i64>, mut right_list: Vec<i64>) -> i64 {
|
||||
// sort lists
|
||||
left_list.sort();
|
||||
@@ -35,6 +47,29 @@ fn calculate_diff(mut left_list: Vec<i64>, mut right_list: Vec<i64>) -> i64 {
|
||||
accumulator
|
||||
}
|
||||
|
||||
/// Part 2
|
||||
///
|
||||
/// This time, you'll need to figure out exactly how often each
|
||||
/// number from the left list appears in the right list. Calculate
|
||||
/// a total similarity score by adding up each number in the left
|
||||
/// list after multiplying it by the number of times that number
|
||||
/// appears in the right list.
|
||||
fn calculate_similarity(left_list: Vec<i64>, right_list: Vec<i64>) -> i64 {
|
||||
// calculate number of occurrences of each id in right list
|
||||
let mut right_occurrences: HashMap<i64, i64> = HashMap::new();
|
||||
for v in right_list {
|
||||
*right_occurrences.entry(v).or_insert(0) += 1;
|
||||
}
|
||||
|
||||
// Accumulate result
|
||||
let mut accumulator = 0;
|
||||
for v in left_list {
|
||||
accumulator += v * right_occurrences.get(&v).unwrap_or(&0);
|
||||
}
|
||||
|
||||
accumulator
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
// Handle command input
|
||||
let args: Vec<String> = env::args().collect();
|
||||
@@ -60,7 +95,14 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
right_list.push(parsed_line.1);
|
||||
}
|
||||
|
||||
println!("Result: {}", calculate_diff(left_list, right_list));
|
||||
println!(
|
||||
"Difference: {}",
|
||||
calculate_diff(left_list.clone(), right_list.clone())
|
||||
);
|
||||
println!(
|
||||
"Similarity: {}",
|
||||
calculate_similarity(left_list, right_list)
|
||||
);
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user