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 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) {
|
||||||
sum += num;
|
adjacent = true;
|
||||||
continue 'entities;
|
if *symbol == '*' {
|
||||||
|
possible_gears
|
||||||
|
.entry((search_row, search_col))
|
||||||
|
.or_default()
|
||||||
|
.push(*num);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if adjacent {
|
||||||
|
sum += num;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
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(())
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue