67 lines
1.8 KiB
Rust
67 lines
1.8 KiB
Rust
advent_of_code::solution!(15);
|
|
|
|
fn hash(input: &str) -> usize {
|
|
let mut cur: usize = 0;
|
|
for c in input.chars() {
|
|
cur = ((cur + c as usize) * 17) % 256;
|
|
}
|
|
cur.try_into().unwrap()
|
|
}
|
|
|
|
pub fn part_one(input: &str) -> Option<usize> {
|
|
Some(input.trim_end().split(",").map(|t| hash(t)).sum())
|
|
}
|
|
|
|
pub fn part_two(input: &str) -> Option<usize> {
|
|
let mut boxes: Vec<Vec<(&str, usize)>> = vec![];
|
|
for _ in 0..256 {
|
|
boxes.push(vec![]);
|
|
}
|
|
for lens in input.trim_end().split(",") {
|
|
if lens.contains("-") {
|
|
let parts = lens.split("-").collect::<Vec<&str>>();
|
|
let h = hash(parts[0]);
|
|
if let Some(index) = boxes[h].iter().position(|t| t.0 == parts[0]) {
|
|
boxes[h].remove(index);
|
|
}
|
|
} else {
|
|
let parts = lens.split("=").collect::<Vec<&str>>();
|
|
let h = hash(parts[0]);
|
|
let n = (parts[0], parts[1].parse::<usize>().unwrap());
|
|
if let Some(index) = boxes[h].iter().position(|t| t.0 == parts[0]) {
|
|
boxes[h][index].1 = n.1;
|
|
} else {
|
|
boxes[h].push(n);
|
|
}
|
|
}
|
|
}
|
|
|
|
let mut sum = 0;
|
|
for (box_index, b) in boxes.iter().enumerate() {
|
|
if b.is_empty() {
|
|
continue;
|
|
}
|
|
for (index, lens) in b.iter().enumerate() {
|
|
sum += (box_index + 1) * (index + 1) * lens.1;
|
|
}
|
|
}
|
|
Some(sum)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn test_part_one() {
|
|
let result = part_one(&advent_of_code::template::read_file("examples", DAY));
|
|
assert_eq!(result, Some(1320));
|
|
}
|
|
|
|
#[test]
|
|
fn test_part_two() {
|
|
let result = part_two(&advent_of_code::template::read_file("examples", DAY));
|
|
assert_eq!(result, Some(145));
|
|
}
|
|
}
|