-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday8.ex
74 lines (64 loc) · 1.78 KB
/
day8.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
defmodule Day8.Part1 do
def run(encoded_image, height, width) do
layer =
encoded_image
|> decode(height, width)
|> find_layer_contain_fewest_0()
count_digit(layer, 1) * count_digit(layer, 2)
end
defp decode(encoded_image, height, width) do
encoded_image
|> String.graphemes()
|> Enum.map(&String.to_integer/1)
|> Enum.chunk_every(height * width)
|> Enum.map(&Enum.chunk_every(&1, width))
end
defp find_layer_contain_fewest_0(layers) do
layers
|> Enum.map(&count_digit(&1, 0))
|> Enum.zip(layers)
|> Enum.min_by(fn {count, _} -> count end)
|> elem(1)
end
defp count_digit(layer, digit) do
layer
|> Enum.flat_map(& &1)
|> Enum.count(&(&1 == digit))
end
end
defmodule Day8.Part2 do
def run(encoded_image, height, width) do
encoded_image
|> decode_image(height, width)
|> render_image(height, width)
|> list_to_string()
end
defp decode_image(encoded_image, height, width) do
encoded_image
|> String.graphemes()
|> Enum.map(&String.to_integer/1)
|> Enum.chunk_every(height * width)
|> Enum.map(&Enum.chunk_every(&1, width))
end
defp render_image(layers, height, width) do
for row <- 0..(height - 1) do
for col <- 0..(width - 1) do
layers
|> Enum.map(fn layer -> layer |> Enum.at(row) |> Enum.at(col) end)
|> Enum.find(&(&1 < 2))
end
end
end
defp list_to_string(list) do
Enum.reduce(list, "", fn row, result ->
line =
Enum.reduce(row, "", fn ele, acc ->
if ele == 0, do: acc <> "□", else: acc <> "■"
end)
result <> "\n" <> line
end)
end
end
File.read!("input.txt")
|> tap(&(Day8.Part1.run(&1, 6, 25) |> IO.inspect(label: "Part 1")))
|> tap(&(Day8.Part2.run(&1, 6, 25) |> IO.puts()))