2023-15: Start implementing part two

This commit is contained in:
Mathis 2023-12-24 01:17:05 +01:00
parent 50e0578690
commit 5444a86e22
2 changed files with 98 additions and 4 deletions

View File

@ -1,5 +1,5 @@
pub mod part_one;
// pub mod part_two;
pub mod part_two;
// pub mod common;
use crate::utils::solution::Solution;
@ -11,7 +11,7 @@ pub struct DaySolution ;
impl Solution for DaySolution {
fn input_path(&self) -> &'static str {
"input/2023/day_15/input.txt"
"input/2023/day_15/input_test.txt"
}
fn part_one(&self) -> String {
@ -19,7 +19,7 @@ impl Solution for DaySolution {
}
fn part_two(&self) -> String {
// input_reader::read_input_file(self.input_path(), part_two::part_two)
String::from("Not implemented")
input_reader::read_input_file(self.input_path(), part_two::part_two)
// String::from("Not implemented")
}
}

View File

@ -0,0 +1,94 @@
use std::collections::HashMap;
pub fn part_two(input_lines: Vec<String>) -> String {
let mut full_line: String = String::new();
for line in input_lines {
full_line.push_str(&line);
}
let init_sequences = full_line.split(',').collect::<Vec<&str>>();
let mut boxes: HashMap<usize, Vec<(String, usize)>> = HashMap::new();
for i in 0..256 {
boxes.insert(i,Vec::new());
}
for seq in init_sequences {
let parsed_seq = parse_sequence(seq);
let hash = hash_sequence(parsed_seq[0].clone());
println!("{}: {:?}", hash, parsed_seq.clone());
if parsed_seq[1] == "=" {
let mut lenses = boxes.get(&hash).unwrap().clone();
let mut found: bool = false;
for i in 0..lenses.len() {
let mut lens = lenses[i].clone();
if lens.0 == parsed_seq[0] {
found = true;
lens.1 = parsed_seq[2].parse().unwrap();
lenses[i] = lens;
boxes.insert(hash, lenses.clone());
break;
}
}
if !found {
lenses.push((parsed_seq[0].to_string(), parsed_seq[2].parse().unwrap()));
boxes.insert(hash, lenses.clone());
}
} else if parsed_seq[1] == "-" {
let mut lenses = boxes.get(&hash).unwrap().clone();
for i in 0..lenses.len() {
let lens = lenses[i].clone();
if lens.0 == parsed_seq[0] {
lenses.remove(i);
boxes.insert(hash, lenses.clone());
break;
}
}
}
}
println!();
for (k, v) in &boxes {
if v.len() > 0 {
println!("{}: {:?}", k, v);
}
}
String::from("Not implemented")
}
fn hash_sequence(sequence: String) -> usize {
let mut hash = 0;
for c in sequence.chars() {
hash += c as usize;
hash *= 17;
hash %= 256;
}
hash
}
fn parse_sequence(sequence: &str) -> Vec<String> {
let mut res: Vec<String> = Vec::new();
let split_sequence: Vec<&str> = sequence.split(['=','-']).collect();
res.push(split_sequence[0].to_string());
if sequence.contains('-') {
res.push('-'.to_string());
} else if sequence.contains('=') {
res.push('='.to_string());
}
if split_sequence.len() > 1 {
res.push(split_sequence[1].to_string());
}
res
}