Advent of Code 2023 - Day 15
I'ts that time of year again, the Advent of Code! I'm completing the challenges this year using Rust 🦀 Day 15 was invigorating after three days of not managing both parts of the challenge!
I'll be posting my solutions here, just to document how I'm solving each challenge, and I highly encourage you to check them out before reading my solutions!
Here's the Day 15 Challenge
BTW: Complete Part 1 to have access to Part 2 😉
Solution for Part 1
use std::fs::File;
use std::io::{Read};
use std::path::Path;
fn main() {
let input_file_path = "path_to_input_file";
let mut curr_sum = 0;
let file = file_as_string(input_file_path)
.unwrap_or_else(|_| panic!("Could not find input file {}", input_file_path));
for str in file.split(',') {
let mut internal_sum : i32 = 0;
for char in str.chars() {
let ascii_code = char.to_ascii_lowercase() as u8;
internal_sum += ascii_code as i32;
internal_sum *= 17;
internal_sum %= 256
}
curr_sum += internal_sum;
}
println!("Sum of all initialization sequence results: {}", curr_sum)
}
fn file_as_string<P: AsRef<Path>>(filename: P) -> std::io::Result<String> {
let mut file = File::open(filename)?;
let mut file_as_str = String::new();
File::read_to_string(&mut file, &mut file_as_str)?;
Ok(file_as_str)
}
Solution for Part 2
use std::collections::HashMap;
use std::fs::File;
use std::io::{Read};
use std::path::Path;
use std::str::FromStr;
fn main() {
let input_file_path = "path_to_input";
let mut curr_sum = 0;
let file = file_as_string(input_file_path)
.unwrap_or_else(|_| panic!("Could not find input file {}", input_file_path));
let mut hashmap: HashMap<i32, Vec<(&str, i8)>> = HashMap::new();
for str in file.split(',') {
if let Some((label, _)) = str.split_once('-') {
let box_name = calculate_hash(label);
let vec = hashmap.entry(box_name).or_insert(Vec::new());
match vec.iter().position(|(el_label, _)| el_label == &label) {
None => {}
Some(idx) => {
vec.remove(idx);
}
}
}
if let Some((label, lens)) = str.split_once('=') {
let box_name = calculate_hash(label);
let vec = hashmap.entry(box_name).or_insert(Vec::new());
let lens_length = i8::from_str(lens).unwrap();
match vec.iter().position(|(el_label, _)| el_label == &label) {
None => {
vec.push((label, lens_length))
}
Some(idx) => {
vec[idx] = (label, lens_length);
}
}
}
}
for (box_number, lenses) in hashmap.iter() {
for (idx, (_, lens)) in lenses.iter().enumerate() {
curr_sum += (box_number + 1) * (idx + 1) as i32 * (*lens as i32);
}
}
println!("Focusing power: {}", curr_sum)
}
fn calculate_hash(str: &str) -> i32 {
let mut internal_sum: i32 = 0;
for char in str.chars() {
let ascii_code = char.to_ascii_lowercase() as u8;
internal_sum += ascii_code as i32;
internal_sum *= 17;
internal_sum %= 256
}
internal_sum
}
fn file_as_string<P: AsRef<Path>>(filename: P) -> std::io::Result<String> {
let mut file = File::open(filename)?;
let mut file_as_str = String::new();
File::read_to_string(&mut file, &mut file_as_str)?;
Ok(file_as_str)
}