day 3 part 2

This commit is contained in:
Dominic 2023-12-03 17:07:13 +01:00
parent 2e0c80df80
commit dbd12f59f1
Signed by: msrd0
GPG key ID: DCC8C247452E98F9

View file

@ -60,27 +60,51 @@ fn main() -> anyhow::Result<()> {
let grid = read("inputs/day3.txt", parser())?; let grid = read("inputs/day3.txt", parser())?;
let mut sum = 0; let mut sum = 0;
let mut possible_gears: HashMap<(usize, usize), Vec<usize>> = HashMap::new();
for (i, line) in grid.iter().enumerate() { for (i, line) in grid.iter().enumerate() {
'entities: for (col, ent) in &line.entities { for (col, ent) in &line.entities {
let Entity::Number { num, len } = ent else { let Entity::Number { num, len } = ent else {
continue; continue;
}; };
// see if adjacent let mut adjacent = false;
for search_row in i.saturating_sub(1) ..= i + 1 { for search_row in i.saturating_sub(1) ..= i + 1 {
let Some(row) = grid.get(search_row) else { let Some(row) = grid.get(search_row) else {
continue; continue;
}; };
for search_col in col.saturating_sub(1) ..= col + len { for search_col in col.saturating_sub(1) ..= col + len {
if let Some(Entity::Symbol(_)) = row.entities.get(&search_col) { if let Some(Entity::Symbol(symbol)) = row.entities.get(&search_col) {
adjacent = true;
if *symbol == '*' {
possible_gears
.entry((search_row, search_col))
.or_default()
.push(*num);
}
}
}
}
if adjacent {
sum += num; sum += num;
continue 'entities;
}
}
} }
} }
} }
println!("{sum}"); println!("{sum}");
println!(
"{}",
possible_gears
.values()
.filter_map(|nums| {
let mut nums = nums.iter();
let ratio = nums.next()? * nums.next()?;
let None = nums.next() else {
return None;
};
Some(ratio)
})
.sum::<usize>()
);
Ok(()) Ok(())
} }