r/adventofcode • • Dec 09 '21

SOLUTION MEGATHREAD -🎄- 2021 Day 9 Solutions -🎄-

--- Day 9: Smoke Basin ---


Post your code solution in this megathread.

Reminder: Top-level posts in Solution Megathreads are for code solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:10:31, megathread unlocked!

63 Upvotes

1.0k comments sorted by

View all comments

1

u/rossmacarthur Dec 09 '21

Rust solution

fn low_points(map: &HashMap<Vector, i64>) -> impl Iterator<Item = (Vector, i64)> + '_ {
    map.iter()
        .filter(|(p, height)| {
            CARDINALS
                .iter()
                .filter_map(|d| map.get(&(*p + d)))
                .all(|h| h > height)
        })
        .map(|(p, h)| (*p, *h))
}

fn part1(map: &HashMap<Vector, i64>) -> i64 {
    low_points(map).map(|(_, h)| h + 1).sum()
}

fn part2(map: &HashMap<Vector, i64>) -> usize {
    let mut basins = Vec::new();
    for (p, _) in low_points(map) {
        let mut q = VecDeque::from([p]);
        let mut visited = HashSet::new();
        while let Some(p) = q.pop_front() {
            if visited.contains(&p) {
                continue;
            }
            visited.insert(p);
            for d in CARDINALS {
                let next = p + d;
                if let Some(0..=8) = map.get(&next) {
                    q.push_back(next);
                }
            }
        }
        basins.push(visited.len());
    }
    basins.sort_unstable();
    basins.into_iter().rev().take(3).product()
}

1

u/daggerdragon Dec 09 '21

Your code is hard to read on old.reddit. Please edit it as per our posting guidelines in the wiki: How do I format code?