NickyMeulemanNime
Metadata
  • Date

  • By

    • Nicky Meuleman
  • Tagged

  • Part of series

  • Older post

    Advent of Code 2022 Day 17

  • Newer post

    Advent of Code 2022 Day 19

Table of contents
  1. Day 18: Boiling Boulders
  2. Parsing
  3. Part 1
    1. Helpers
    2. Final code
  4. Part 2
    1. Helpers
    2. Final code
  5. Final code

Advent of Code 2022 Day 18

Day 18: Boiling Boulders

https://adventofcode.com/2022/day/18

You exit the vulcano.

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:

input.txt
2,2,2
1,2,2
3,2,2
2,1,2
2,3,2
2,2,1
2,2,3
2,2,4
2,2,6
1,2,5
3,2,5
2,1,5
2,3,5

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!

day_18.rs
use std::collections::HashSet;
#[derive(Hash, PartialEq, Eq, Clone, Copy, Default)]
struct Coord {
x: i16,
y: i16,
z: i16,
}
fn parse() -> HashSet<Coord> {
let input = std::fs::read_to_string("src/day18.txt").unwrap();
input
.lines()
.map(|line| {
let mut nums = line.split(",").map(|s| s.parse().unwrap());
Coord {
x: nums.next().unwrap(),
y: nums.next().unwrap(),
z: nums.next().unwrap(),
}
})
.collect()
}

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:

pseudocode.rs
let cubes = parse();
cubes
.iter()
.flat_map(|coord| coord.neighbours())
// only keep neighbours that are not a cube
.filter(|coord| !cubes.contains(coord))
.count()

Helpers

The goal is to define that neighbours method from the skeleton code.

But first, an enum to represent the three dimensions!

enum Dimension {
X,
Y,
Z,
}

Ok, ok. NOW the neighbours method.

impl Coord {
fn neighbours(&self) -> Vec<Coord> {
let mut neighbours = Vec::new();
// loop over every dimension in a cube
for dimension in [Dimension::X, Dimension::Y, Dimension::Z] {
// add or remove 1 to coordinate in current dimension
for offset in [-1, 1] {
// resulting coordinates are from the coord to a side of a cube
let mut neighbour = self.clone();
match dimension {
Dimension::X => neighbour.x += offset,
Dimension::Y => neighbour.y += offset,
Dimension::Z => neighbour.z += offset,
}
neighbours.push(neighbour);
}
}
neighbours
}
}

Here’s an alternative that returns an iterator, uses Itertools, and uses the struct update syntax

fn neighbours(&self) -> impl Iterator<Item = Coord> + '_ {
[Dimension::X, Dimension::Y, Dimension::Z]
.iter()
.cartesian_product([-1, 1])
.map(|(dimension, offset)| match dimension {
Dimension::X => Coord {
x: self.x + offset,
..*self
},
Dimension::Y => Coord {
y: self.y + offset,
..*self
},
Dimension::Z => Coord {
z: self.z + offset,
..*self
},
})
}

With this helper, the skeleton code above is exactly the final code for part1.

Final code

day_18.rs
pub fn part_1() -> usize {
let cubes = parse();
cubes
.iter()
.flat_map(|coord| coord.neighbours())
// only keep neighbours that are not a cube
.filter(|coord| !cubes.contains(coord))
.count()
}

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:

skeleton.rs
let cubes = parse();
let exposed = exposed(&cubes);
cubes
.iter()
.flat_map(|coord| coord.neighbours())
// only keep neighbours that are also exposed
.filter(|coord| exposed.contains(coord))
.count()

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.

fn bounds(cubes: &HashSet<Coord>) -> [Coord; 2] {
cubes.iter().fold(
[Coord::default(), Coord::default()],
|[mut mins, mut maxs], cube| {
mins.x = mins.x.min(cube.x);
mins.y = mins.y.min(cube.y);
mins.z = mins.z.min(cube.z);
maxs.x = maxs.x.max(cube.x);
maxs.y = maxs.y.max(cube.y);
maxs.z = maxs.z.max(cube.z);
[mins, maxs]
},
)
}

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.

fn exposed(cubes: &HashSet<Coord>) -> HashSet<Coord> {
let bounds = bounds(cubes);
let mut exposed = HashSet::new();
let start = Coord::default();
let mut stack = Vec::new();
let mut seen = HashSet::new();
stack.push(start);
seen.insert(start);
while let Some(coord) = stack.pop() {
for neighbour in coord.neighbours() {
if cubes.contains(&neighbour) || !neighbour.in_bounds(&bounds) {
continue;
}
if seen.insert(neighbour) {
stack.push(neighbour);
exposed.insert(neighbour);
}
}
}
exposed
}

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.

fn in_bounds(&self, bounds: &[Self; 2]) -> bool {
let [mins, maxs] = bounds;
self.x >= mins.x - 1
&& self.x <= maxs.x + 1
&& self.y >= mins.y - 1
&& self.y <= maxs.y + 1
&& self.z >= mins.z - 1
&& self.z <= maxs.z + 1
}

With those helpers, the skeleton code above is exactly the final code for part2.

Final code

day_18.rs
pub fn part_2() -> usize {
let cubes = parse();
let exposed = exposed(&cubes);
cubes
.iter()
.flat_map(|coord| coord.neighbours())
// only keep neighbours that are also exposed
.filter(|coord| exposed.contains(coord))
.count()
}

Final code

day_18.rs
1use std::collections::HashSet;
2
3use itertools::Itertools;
4
5#[derive(Hash, PartialEq, Eq, Clone, Copy, Default)]
6struct Coord {
7 x: i16,
8 y: i16,
9 z: i16,
10}
11
12impl Coord {
13 fn neighbours(&self) -> impl Iterator<Item = Coord> + '_ {
14 [Dimension::X, Dimension::Y, Dimension::Z]
15 .iter()
16 .cartesian_product([-1, 1])
17 .map(|(dimension, offset)| match dimension {
18 Dimension::X => Coord {
19 x: self.x + offset,
20 ..*self
21 },
22 Dimension::Y => Coord {
23 y: self.y + offset,
24 ..*self
25 },
26 Dimension::Z => Coord {
27 z: self.z + offset,
28 ..*self
29 },
30 })
31 }
32
33 fn in_bounds(&self, bounds: &[Self; 2]) -> bool {
34 let [mins, maxs] = bounds;
35 self.x >= mins.x - 1
36 && self.x <= maxs.x + 1
37 && self.y >= mins.y - 1
38 && self.y <= maxs.y + 1
39 && self.z >= mins.z - 1
40 && self.z <= maxs.z + 1
41 }
42}
43
44enum Dimension {
45 X,
46 Y,
47 Z,
48}
49
50fn parse() -> HashSet<Coord> {
51 let input = std::fs::read_to_string("src/day18.txt").unwrap();
52
53 input
54 .lines()
55 .map(|line| {
56 let mut nums = line.split(",").map(|s| s.parse().unwrap());
57 Coord {
58 x: nums.next().unwrap(),
59 y: nums.next().unwrap(),
60 z: nums.next().unwrap(),
61 }
62 })
63 .collect()
64}
65
66fn bounds(cubes: &HashSet<Coord>) -> [Coord; 2] {
67 cubes.iter().fold(
68 [Coord::default(), Coord::default()],
69 |[mut mins, mut maxs], cube| {
70 mins.x = mins.x.min(cube.x);
71 mins.y = mins.y.min(cube.y);
72 mins.z = mins.z.min(cube.z);
73 maxs.x = maxs.x.max(cube.x);
74 maxs.y = maxs.y.max(cube.y);
75 maxs.z = maxs.z.max(cube.z);
76 [mins, maxs]
77 },
78 )
79}
80
81fn exposed(cubes: &HashSet<Coord>) -> HashSet<Coord> {
82 let bounds = bounds(cubes);
83 let mut exposed = HashSet::new();
84
85 let start = Coord::default();
86 let mut stack = Vec::new();
87 let mut seen = HashSet::new();
88
89 stack.push(start);
90 seen.insert(start);
91
92 while let Some(coord) = stack.pop() {
93 for neighbour in coord.neighbours() {
94 if cubes.contains(&neighbour) || !neighbour.in_bounds(&bounds) {
95 continue;
96 }
97 if seen.insert(neighbour) {
98 stack.push(neighbour);
99 exposed.insert(neighbour);
100 }
101 }
102 }
103
104 exposed
105}
106
107pub fn part_1() -> usize {
108 let cubes = parse();
109
110 cubes
111 .iter()
112 .flat_map(|coord| coord.neighbours())
113 // only keep neighbours that are not a cube
114 .filter(|coord| !cubes.contains(coord))
115 .count()
116}
117
118pub fn part_2() -> usize {
119 let cubes = parse();
120 let exposed = exposed(&cubes);
121
122 cubes
123 .iter()
124 .flat_map(|coord| coord.neighbours())
125 // only keep neighbours that are also exposed
126 .filter(|coord| exposed.contains(coord))
127 .count()
128}

Series navigation for: Advent of Code 2022

1. Advent of Code 2022 Day 1

Designed and developed by Nicky Meuleman

Built with Gatsby. Hosted on Netlify.