1
0
Fork 0

day15 solution

main
Andrew Coleman 2023-12-27 17:05:57 -05:00
parent 95003d0b0a
commit b6111fe337
2 changed files with 65 additions and 0 deletions

64
2023/src/day15.rs Normal file
View File

@ -0,0 +1,64 @@
use aoc_runner_derive::aoc;
fn hash(input: &str) -> usize {
let mut cur: usize = 0;
for c in input.chars() {
cur = ((cur + c as usize) * 17) % 256;
}
cur
}
#[aoc(day15, part1)]
fn part1(input: &str) -> usize {
input.trim_end().split(",").map(|t| hash(t)).sum()
}
#[aoc(day15, part2)]
fn part2(input: &str) -> 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;
}
}
sum
}
#[cfg(test)]
mod tests {
use super::*;
const SAMPLE_DATA: &'static str = "rn=1,cm-,qp=3,cm=2,qp-,pc=4,ot=9,ab=5,pc-,pc=6,ot=7";
#[test]
fn sample_data() {
assert_eq!(part1(&SAMPLE_DATA), 1320);
assert_eq!(part2(&SAMPLE_DATA), 145);
}
}

View File

@ -14,5 +14,6 @@ mod day11;
mod day12;
mod day13;
mod day14;
mod day15;
aoc_lib! { year = 2023 }