A piece of lava (it’s above ground now, magma no more!) flies past you.
Your device quickly scans it.
It’s in low resolution and it approximates the droplet of lava as a bunch of 1x1x1 cubes on a 3D grid.
That’s todays input.
An example input looks like this:
Parsing
That’s right, it’s time for Coord!
3D ones today!
I want to put all the coordinates in a set, so I derive a few things.
Coordinates can get negative, so signed integers as coordinates it is!
Part 1
The question asks what the surface area of your scanned lava droplet is.
To get that surface area, count the number of sides of each cube that are not immediately connected to another cube.
For every coordinate in the droplet, I want to count the amount of neighbouring coordinates that are not in the droplet.
In skeleton code:
Helpers
The goal is to define that neighbours method from the skeleton code.
But first, an enum to represent the three dimensions!
Ok, ok. NOW the neighbours method.
Here’s an alternative that returns an iterator, uses Itertools, and uses the struct update syntax
With this helper, the skeleton code above is exactly the final code for part1.
Final code
Part 2
The question asks what the surface area of your scanned lava droplet is.
That’s exactly the same question as part1?!
This time, only consider sides that can be reached from the outside and ignore trapped pockets of air.
skeleton code:
That’s 1 extra method (exposed), and a slight logic change in the step where we choose what to filter.
The exposed in that code is the collection of all coordinates that are reachable from outside.
Because we can’t represent literally all coordinates outside, we calculate all the ones in a bounding box the lava droplet would barely fit in.
Helpers
An extra function to return all maxima and minima in the set of scanned coordinates.
Now the most interesting function: exposed().
It runs a floodfill algorithm that starts filling at Coord { x: 0, y: 0, z: 0 }.
The result is every coordinate (within the bounds plus and minus one!) that is not blocked by the lava droplet.
in_bounds is a method on Coord that returns true if the checked Coord has coordinates that are at most one more, or one less than the bounds in any dimension.
With those helpers, the skeleton code above is exactly the final code for part2.