2022-12-05 20:23:57 +01:00
|
|
|
use std::collections::HashSet;
|
|
|
|
|
2022-12-05 22:04:14 +01:00
|
|
|
fn character_to_code(input: i32) -> i32 {
|
|
|
|
if input >= ('a' as i32) {
|
|
|
|
input - 96
|
|
|
|
} else {
|
|
|
|
input - 38
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-05 20:23:57 +01:00
|
|
|
pub fn solve_part1(file_path: &str) -> i32 {
|
|
|
|
let binding =
|
|
|
|
std::fs::read_to_string(file_path).expect("Please provide a text file as an argument.");
|
2022-12-05 21:55:28 +01:00
|
|
|
binding
|
2022-12-05 20:23:57 +01:00
|
|
|
.lines()
|
|
|
|
.collect::<Vec<&str>>()
|
|
|
|
.iter()
|
|
|
|
.map(|item: &&str| {
|
|
|
|
let (first, last) = item.split_at(item.len() / 2);
|
|
|
|
let second = last.chars().collect::<HashSet<char>>();
|
|
|
|
let intersection = first.chars().collect::<HashSet<char>>();
|
2022-12-05 22:37:05 +01:00
|
|
|
let character = *intersection
|
|
|
|
.intersection(&second)
|
|
|
|
.next()
|
|
|
|
.unwrap_or(&(0 as char)) as i32;
|
2022-12-05 22:04:14 +01:00
|
|
|
character_to_code(character)
|
2022-12-05 20:23:57 +01:00
|
|
|
})
|
2022-12-05 21:55:28 +01:00
|
|
|
.collect::<Vec<i32>>()
|
|
|
|
.iter()
|
|
|
|
.sum::<i32>()
|
2022-12-05 20:23:57 +01:00
|
|
|
}
|
2022-12-05 22:37:05 +01:00
|
|
|
|
|
|
|
pub fn solve_part2(file_path: &str) -> i32 {
|
|
|
|
let binding =
|
|
|
|
std::fs::read_to_string(file_path).expect("Please provide a text file as an argument.");
|
|
|
|
let mut iter = binding.lines();
|
|
|
|
binding
|
|
|
|
.lines()
|
|
|
|
.step_by(3)
|
|
|
|
.collect::<Vec<&str>>()
|
|
|
|
.iter()
|
2022-12-05 22:37:35 +01:00
|
|
|
.map(|_item| {
|
2022-12-05 22:37:05 +01:00
|
|
|
let common_letter = {
|
|
|
|
let first = &iter
|
|
|
|
.next()
|
|
|
|
.expect("Expected a string, not nothing.")
|
|
|
|
.chars()
|
|
|
|
.collect::<HashSet<char>>()
|
|
|
|
& &iter
|
|
|
|
.next()
|
|
|
|
.expect("Expected a string, not nothing.")
|
|
|
|
.chars()
|
|
|
|
.collect::<HashSet<char>>();
|
|
|
|
&first
|
|
|
|
& &iter
|
|
|
|
.next()
|
|
|
|
.expect("Expected a string, not nothing.")
|
|
|
|
.chars()
|
|
|
|
.collect::<HashSet<char>>()
|
|
|
|
};
|
|
|
|
if !common_letter.is_empty() && common_letter.len() > 1 {
|
|
|
|
panic!("Anormal behavior. Must have only 1 element in {common_letter:?}");
|
|
|
|
} else {
|
|
|
|
let unique_letter = *common_letter
|
|
|
|
.iter()
|
|
|
|
.last()
|
|
|
|
.expect("Impossible to have this message else Rust has a problem...")
|
|
|
|
as i32;
|
|
|
|
character_to_code(unique_letter)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.collect::<Vec<i32>>()
|
|
|
|
.iter()
|
|
|
|
.sum::<i32>()
|
|
|
|
}
|