-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathday_08.ex
70 lines (61 loc) · 1.47 KB
/
day_08.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
defmodule AdventOfCode.Y2019.Day08 do
@moduledoc """
--- Day 8: Space Image Format ---
Problem Link: https://adventofcode.com/2019/day/8
Difficulty: xs
Tags: sequence visual-result
"""
alias AdventOfCode.Helpers.InputReader
@width 25
@height 6
@printchar "▒"
def input, do: InputReader.read_from_file(2019, 8)
def run(input \\ input()) do
input = parse(input)
run_2(input)
{run_1(input), :ok}
end
def run_1(input) do
input
|> Enum.map(fn layer -> Enum.flat_map(layer, & &1) end)
|> Enum.min_by(&Enum.count(&1, fn x -> x == 0 end))
|> then(fn x -> Enum.count(x, &(&1 == 2)) * Enum.count(x, &(&1 == 1)) end)
end
def run_2(input) do
input
|> Enum.map(fn layer -> Enum.flat_map(layer, & &1) end)
|> Enum.reduce(&overlay(&2, &1))
|> Enum.join()
|> print_image()
end
def parse(data) do
data
|> String.graphemes()
|> Enum.map(&String.to_integer/1)
|> chunkify()
end
defp overlay(layer_1, layer_2) do
layer_1
|> Enum.zip(layer_2)
|> Enum.map(fn
{2, x} -> x
{1, _} -> 1
{0, _} -> 0
end)
end
defp print_image(data) do
data
|> String.replace("1", @printchar)
|> String.replace("0", " ")
|> String.codepoints()
|> chunkify()
|> List.first()
|> Enum.map_join("\n", &Enum.join/1)
|> tap(&IO.puts/1)
end
defp chunkify(data) do
data
|> Enum.chunk_every(@width * @height)
|> Enum.map(&Enum.chunk_every(&1, @width))
end
end