this repo has no description
1<!-- vim:set ft=markdown: -->
2
3<!-- livebook:{"persist_outputs":true} -->
4
5# Day 8
6
7```elixir
8input =
9 File.stream!("day8.txt")
10 |> Stream.map(fn line ->
11 line
12 |> String.split(" | ")
13 |> Enum.map(fn part ->
14 part
15 |> String.trim()
16 |> String.split(" ")
17 |> Enum.map(fn disp ->
18 # Sort characters in each entry to simplify later work
19 disp
20 |> String.to_charlist()
21 |> Enum.sort()
22 |> List.to_string()
23 end)
24 end)
25 |> List.to_tuple()
26 end)
27```
28
29```output
30#Stream<[
31 enum: %File.Stream{
32 line_or_bytes: :line,
33 modes: [:raw, :read_ahead, :binary],
34 path: "day8.txt",
35 raw: true
36 },
37 funs: [#Function<47.58486609/1 in Stream.map/2>]
38]>
39```
40
41## Task 1
42
43We simply need to count all occurences of the values that have 2, 3, 4, or 7 highlighted
44segments.
45
46```elixir
47input
48|> Enum.map(fn {_, output} ->
49 Enum.count(output, &(byte_size(&1) in [2, 3, 4, 7]))
50end)
51|> Enum.sum()
52```
53
54```output
55390
56```
57
58## Task 2
59
60```elixir
61defmodule Day8.Task2 do
62 defp a --- b, do: MapSet.difference(a, b)
63
64 defp a +++ b, do: MapSet.union(a, b)
65
66 defp a <~> b, do: MapSet.intersection(a, b)
67
68 # 1. 7. 4. 2|3|5. 2|3|5. 2|3|5. 6|9|0. 6|9|0. 6|9|0. 8.
69 def deduce([cf, acf, bcdf, acdeg, acdfg, abdfg, abdefg, abcdfg, abcefg, abcdefg]) do
70 eg = abcdefg --- (acf +++ bcdf)
71 bd = bcdf --- cf
72 adg = acdeg <~> acdfg <~> abdfg
73 abfg = abdefg <~> abcdfg <~> abcefg
74 a = acf --- cf
75 b = abfg <~> bd
76 f = abfg <~> cf
77 g = adg <~> eg
78 d = adg <~> bd
79 c = cf --- f
80 e = eg --- g
81
82 [a, b, c, d, e, f, g] =
83 [a, b, c, d, e, f, g]
84 |> Enum.map(&extract/1)
85
86 [
87 # 0
88 [a, b, c, e, f, g],
89 # 1
90 [c, f],
91 # 2
92 [a, c, d, e, g],
93 # 3
94 [a, c, d, f, g],
95 # 4
96 [b, c, d, f],
97 # 5
98 [a, b, d, f, g],
99 # 6
100 [a, b, d, e, f, g],
101 # 7
102 [a, c, f],
103 # 8
104 [a, b, c, d, e, f, g],
105 # 9
106 [a, b, c, d, f, g]
107 ]
108 |> Enum.map(&List.to_string(Enum.sort(&1)))
109 |> Enum.with_index()
110 |> Map.new()
111 end
112
113 defp extract(a) do
114 # Just additional sanity check
115 [v] = MapSet.to_list(a)
116
117 v
118 end
119
120 def decode(matches, output) do
121 output
122 |> Enum.map(&matches[&1])
123 |> Integer.undigits()
124 end
125end
126
127input
128|> Enum.map(fn {input, output} ->
129 input
130 |> Enum.sort_by(&byte_size/1)
131 |> Enum.map(&MapSet.new(String.to_charlist(&1)))
132 |> Day8.Task2.deduce()
133 |> Day8.Task2.decode(output)
134end)
135|> Enum.sum()
136```
137
138```output
1391011785
140```