day 3 part 2
This commit is contained in:
parent
2e0c80df80
commit
dbd12f59f1
1 changed files with 29 additions and 5 deletions
|
@ -60,27 +60,51 @@ fn main() -> anyhow::Result<()> {
|
|||
let grid = read("inputs/day3.txt", parser())?;
|
||||
|
||||
let mut sum = 0;
|
||||
let mut possible_gears: HashMap<(usize, usize), Vec<usize>> = HashMap::new();
|
||||
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 {
|
||||
continue;
|
||||
};
|
||||
|
||||
// see if adjacent
|
||||
let mut adjacent = false;
|
||||
for search_row in i.saturating_sub(1) ..= i + 1 {
|
||||
let Some(row) = grid.get(search_row) else {
|
||||
continue;
|
||||
};
|
||||
for search_col in col.saturating_sub(1) ..= col + len {
|
||||
if let Some(Entity::Symbol(_)) = row.entities.get(&search_col) {
|
||||
sum += num;
|
||||
continue 'entities;
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
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(())
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue