Mix.install([
{:kino, "~> 0.14.2"}
])
input = Kino.Input.textarea("Please, paste your input:")
defmodule Day12Shared do
def parse(input) do
map =
input
|> Kino.Input.read()
|> String.split("\n")
|> Enum.with_index()
|> Enum.reduce(%{}, fn {row, y}, map ->
row
|> String.codepoints()
|> Enum.with_index()
|> Enum.reduce(map, fn {value, x}, map ->
map
|> Map.put({x, y}, value)
|> Map.update(:max_x, x, &max(&1, x))
|> Map.update(:max_y, y, &max(&1, y))
end)
end)
{map, build_graph(map)}
end
defp build_graph(map) do
Enum.reduce(map, %{}, fn {coord, plant_type}, graph ->
possible_moves =
coord
|> neibs()
|> Enum.filter(fn neib -> Map.get(map, neib) == plant_type end)
Map.put(graph, coord, possible_moves)
end)
end
defp neibs({x, y}), do: [{x, y - 1}, {x + 1, y}, {x, y + 1}, {x - 1, y}]
defp neibs(_), do: []
def locate_regions(%{max_x: max_x, max_y: max_y} = map, graph) do
to_categorize = for x <- 0..max_x, y <- 0..max_y, do: {x, y}
locate_regions(map, graph, to_categorize, [])
end
defp locate_regions(_map, _graph, [], regions), do: regions
defp locate_regions(map, graph, [coord | to_categorize], regions) do
region = bfs(graph, [coord], MapSet.new([coord]))
locate_regions(map, graph, to_categorize -- MapSet.to_list(region), [region | regions])
end
defp bfs(_graph, [], visited), do: visited
defp bfs(graph, [node | routes], visited) do
next = Enum.filter(graph[node], &(!MapSet.member?(visited, &1)))
new_routes = routes ++ next
visited = MapSet.union(visited, MapSet.new(next))
bfs(graph, new_routes, visited)
end
end
# Day12Shared.parse(input)
Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search.
You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots.
Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example:
AAAA
BBCD
BBCC
EEEC
This 4x4 arrangement includes garden plots growing five different types of plants (labeled A
, B
, C
, D
, and E
), each grouped into their own region.
In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter.
The area of a region is simply the number of garden plots the region contains. The above map's type A
, B
, and C
plants are each in a region of area 4
. The type E
plants are in a region of area 3
; the type D
plants are in a region of area 1
.
Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A
and C
plants are each in a region with perimeter 10
. The type B
and E
plants are each in a region with perimeter 8
. The lone D
plot forms its own region with perimeter 4
.
Visually indicating the sides of plots in each region that contribute to the perimeter using -
and |
, the above map's regions' perimeters are measured as follows:
+-+-+-+-+
|A A A A|
+-+-+-+-+ +-+
|D|
+-+-+ +-+ +-+
|B B| |C|
+ + + +-+
|B B| |C C|
+-+-+ +-+ +
|C|
+-+-+-+ +-+
|E E E|
+-+-+-+
Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example:
OOOOO
OXOXO
OOOOO
OXOXO
OOOOO
The above map contains five regions, one containing all of the O
garden plots, and the other four each containing a single X
plot.
The four X
regions each have area 1
and perimeter 4
. The region containing 21
type O
plants is more complicated; in addition to its outer edge contributing a perimeter of 20
, its boundary with each X
region contributes an additional 4
to its perimeter, for a total perimeter of 36
.
Due to "modern" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map.
In the first example, region A
has price 4 * 10 = 40
, region B
has price 4 * 8 = 32
, region C
has price 4 * 10 = 40
, region D
has price 1 * 4 = 4
, and region E
has price 3 * 8 = 24
. So, the total price for the first example is 140
.
In the second example, the region with all of the O
plants has price 21 * 36 = 756
, and each of the four smaller X
regions has price 1 * 4 = 4
, for a total price of 772
(756 + 4 + 4 + 4 + 4
).
Here's a larger example:
RRRRIICCFF
RRRRIICCCF
VVRRRCCFFF
VVRCCCJFFF
VVVVCJJCFE
VVIVCCJJEE
VVIIICJJEE
MIIIIIJJEE
MIIISIJEEE
MMMISSJEEE
It contains:
- A region of
R
plants with price12 * 18 = 216
. - A region of
I
plants with price4 * 8 = 32
. - A region of
C
plants with price14 * 28 = 392
. - A region of
F
plants with price10 * 18 = 180
. - A region of
V
plants with price13 * 20 = 260
. - A region of
J
plants with price11 * 20 = 220
. - A region of
C
plants with price1 * 4 = 4
. - A region of
E
plants with price13 * 18 = 234
. - A region of
I
plants with price14 * 22 = 308
. - A region of
M
plants with price5 * 12 = 60
. - A region of
S
plants with price3 * 8 = 24
.
So, it has a total price of 1930
.
What is the total price of fencing all regions on your map?
defmodule Day12Part1 do
import Day12Shared, only: [locate_regions: 2]
def process({map, graph}) do
map
|> locate_regions(graph)
|> Enum.map(&cost(graph, &1))
|> Enum.reduce(0, fn {perimeter, area}, total_cost ->
total_cost + perimeter * area
end)
end
def cost(graph, region) do
# How to find a perimeter of a plant field? It's 4 if none neighbors aroun, and it's less
# than 4 by the number of neighbors...
perimeter = Enum.reduce(region, 0, fn coord, acc ->
acc + (4 - Enum.count(graph[coord]))
end)
area = MapSet.size(region)
{perimeter, area}
end
end
input |> Day12Shared.parse() |> Day12Part1.process()
# 1437300 is the right answer
Fortunately, the Elves are trying to order so much fence that they qualify for a bulk discount!
Under the bulk discount, instead of using the perimeter to calculate the price, you need to use the number of sides each region has. Each straight section of fence counts as a side, regardless of how long it is.
Consider this example again:
AAAA
BBCD
BBCC
EEEC
The region containing type A
plants has 4
sides, as does each of the regions containing plants of type B
, D
, and E
. However, the more complex region containing the plants of type C
has 8
sides!
Using the new method of calculating the per-region price by multiplying the region's area by its number of sides, regions A
through E
have prices 16
, 16
, 32
, 4
, and 12
, respectively, for a total price of 80
.
The second example above (full of type X
and O
plants) would have a total price of 436
.
Here's a map that includes an E-shaped region full of type E
plants:
EEEEE
EXXXX
EEEEE
EXXXX
EEEEE
The E-shaped region has an area of 17
and 12
sides for a price of 204
. Including the two regions full of type X
plants, this map has a total price of 236
.
This map has a total price of 368
:
AAAAAA
AAABBA
AAABBA
ABBAAA
ABBAAA
AAAAAA
It includes two regions full of type B
plants (each with 4
sides) and a single region full of type A
plants (with 4
sides on the outside and 8
more sides on the inside, a total of 12
sides). Be especially careful when counting the fence around regions like the one full of type A
plants; in particular, each section of fence has an in-side and an out-side, so the fence does not connect across the middle of the region (where the two B
regions touch diagonally). (The Elves would have used the Möbius Fencing Company instead, but their contract terms were too one-sided.)
The larger example from before now has the following updated prices:
- A region of
R
plants with price12 * 10 = 120
. - A region of
I
plants with price4 * 4 = 16
. - A region of
C
plants with price14 * 22 = 308
. - A region of
F
plants with price10 * 12 = 120
. - A region of
V
plants with price13 * 10 = 130
. - A region of
J
plants with price11 * 12 = 132
. - A region of
C
plants with price1 * 4 = 4
. - A region of
E
plants with price13 * 8 = 104
. - A region of
I
plants with price14 * 16 = 224
. - A region of
M
plants with price5 * 6 = 30
. - A region of
S
plants with price3 * 6 = 18
.
Adding these together produces its new total price of 1206
.
What is the new total price of fencing all regions on your map?
defmodule Day12Part2 do
import Day12Shared, only: [locate_regions: 2]
def process({map, graph}) do
map
|> locate_regions(graph)
|> Enum.map(&cost/1)
|> Enum.reduce(0, fn {sides_n, area}, total_cost ->
total_cost + sides_n * area
end)
end
def cost(region) do
{v_sides, v_sides} = sides(region)
area = MapSet.size(region)
{v_sides + v_sides, area}
end
# Finds all the horizontal and vertical sides for a region. How?
# We find a bounding box (min/max coordinates) for the region and "scan" it vertically
# and horizontally.
defp sides(region) do
# the 9001 is just an arbitrary number that is (definitely) more than size of a garden map,
# so we can use it for min X and Y to get the box limits
{{min_x, max_x}, {min_y, max_y}} =
Enum.reduce(region, {{9001, 0}, {9001, 0}}, fn {x, y}, {{min_x, max_x}, {min_y, max_y}} ->
{{min(x, min_x), max(x, max_x)}, {min(y, min_y), max(y, max_y)}}
end)
# now we can "scan" the region
{
v_edges(region, min_x, max_x + 1, []),
h_edges(region, min_y, max_y + 1, [])
}
end
# The rest of the code is not the best (but it does what it should), so we can explain
# what is happening there.
#
# *_edges function take the region they're counting edges for, min and max coordinate to
# scan (from-to) and accumulator.
#
# The v-functions use X coordinate, while h-functions use Y. They take a straight line,
# filter plants in the region on this line only, find out if it has any neighbors (for
# v-edges we need to know about left and right ones, for h-edges – top and bottom), then
# we collect all that information into a map, which can be used to count the actual sides.
#
# We count sides as one if they consequtive (previous X or Y coordinate changes smoothly
# by 1), and increase number of there is a gap.
#
# Visually, our scanning of a region can presented something like this:
#
# 1 2 3
# v v v
# | | |
# | | |
# +-+-+-+
# 5 > - - | | - -
# + +-+
# 6 > - - | | - -
# + +-+
# 7 > - - | | - -
# +-+-+-+
# | | |
# | | |
def v_edges(_, same_x, same_x, sides) do
Enum.sum(sides)
end
def v_edges(region, x, max_x, plots) do
plots_with_edges =
region
|> Enum.filter(fn {px, _y} -> px == x end)
|> Enum.map(fn {x, y} ->
{
{x, y},
MapSet.member?(region, {x - 1, y}),
MapSet.member?(region, {x + 1, y})
}
end)
|> Enum.reduce(%{left: [], right: []}, fn {plot, has_left_neib, has_right_neib}, acc ->
case {has_left_neib, has_right_neib} do
{false, true} ->
Map.update!(acc, :left, &[plot | &1])
{true, false} ->
Map.update!(acc, :right, &[plot | &1])
{false, false} ->
acc |> Map.update!(:left, &[plot | &1]) |> Map.update!(:right, &[plot | &1])
{true, true} ->
acc
end
end)
left_sides = count_v_edges(plots_with_edges, :left)
right_sides = count_v_edges(plots_with_edges, :right)
v_edges(region, x + 1, max_x, [left_sides + right_sides | plots])
end
defp count_v_edges(plots, left_or_right) do
plots
|> Map.fetch!(left_or_right)
|> Enum.sort_by(&elem(&1, 1))
|> Enum.reduce({0, :start}, fn
{_, y}, {0, :start} -> {1, y}
{_, y}, {count, prev_y} when y - prev_y == 1 -> {count, y}
{_, y}, {count, _} -> {count + 1, y}
end)
|> elem(0)
end
def h_edges(_, same_y, same_y, sides) do
Enum.sum(sides)
end
def h_edges(region, y, max_y, plots) do
plots_with_edges =
region
|> Enum.filter(fn {_x, py} -> py == y end)
|> Enum.map(fn {x, y} ->
{
{x, y},
MapSet.member?(region, {x, y - 1}),
MapSet.member?(region, {x, y + 1})
}
end)
|> Enum.reduce(%{top: [], bottom: []}, fn {plot, has_top_neib, has_bottom_neib}, acc ->
case {has_top_neib, has_bottom_neib} do
{false, true} ->
Map.update!(acc, :top, &[plot | &1])
{true, false} ->
Map.update!(acc, :bottom, &[plot | &1])
{false, false} ->
acc |> Map.update!(:top, &[plot | &1]) |> Map.update!(:bottom, &[plot | &1])
{true, true} ->
acc
end
end)
top_sides = count_h_edges(plots_with_edges, :top)
bottom_sides = count_h_edges(plots_with_edges, :bottom)
h_edges(region, y + 1, max_y, [top_sides + bottom_sides | plots])
end
defp count_h_edges(plots, top_or_bottom) do
plots
|> Map.fetch!(top_or_bottom)
|> Enum.sort_by(&elem(&1, 0))
|> Enum.reduce({0, :start}, fn
{x, _}, {0, :start} -> {1, x}
{x, _}, {count, prev_x} when x - prev_x == 1 -> {count, x}
{x, _}, {count, _} -> {count + 1, x}
end)
|> elem(0)
end
end
input |> Day12Shared.parse() |> Day12Part2.process()
# 849332 is the right answer