Skip to content

Instantly share code, notes, and snippets.

@Trivaxy
Created December 10, 2023 17:39
Show Gist options
  • Save Trivaxy/31f9ac063629615117e3040e7243a149 to your computer and use it in GitHub Desktop.
Save Trivaxy/31f9ac063629615117e3040e7243a149 to your computer and use it in GitHub Desktop.
use std::collections::{HashMap, HashSet};
use crate::util::Grid;
// just pretend you know what Grid does
pub fn part_1(input: &str) -> u32 {
let grid = Grid::create(input);
let mut sum = 0;
for y in 0..grid.height() {
let mut curr = 0;
let mut is_part = false;
for x in 0..grid.width() {
if let Some(n) = grid.at(x, y).as_digit() {
curr = curr * 10 + n;
if grid.at(x, y).count_adjacent(|c| !c.is_ascii_digit() && c != '.') > 0 {
is_part = true;
}
} else {
if is_part { sum += curr; }
is_part = false;
curr = 0;
}
}
}
sum
}
pub fn part_2(input: &str) -> u64 {
let grid = Grid::create(input);
let mut entries = HashMap::new();
for y in 0..grid.height() {
let mut touching = HashSet::new();
let mut curr = 0;
for x in 0..=grid.width() {
if let Some(n) = grid.at(x, y).as_digit() {
curr = curr * 10 + n as u64;
grid.at(x, y).for_adjacent(|c, i, j| {
if c == '*' { touching.insert((i, j)); }
});
} else {
touching.iter().for_each(|(i, j)| {
entries.entry((*i, *j)).or_insert(Vec::new()).push(curr);
});
curr = 0;
touching.clear();
}
}
}
entries.values().filter(|v| v.len() == 2).map(|v| v[0] * v[1]).sum()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment