+13
-18
2022/day05.livemd
+13
-18
2022/day05.livemd
···
37
37
moves
38
38
|> String.split("\n", trim: true)
39
39
|> Enum.map(fn move ->
40
-
result = Regex.named_captures(~r/move (?<count>\d+) from (?<from>\d) to (?<to>\d)/, move)
41
-
42
-
%{
43
-
count: String.to_integer(result["count"]),
44
-
from: String.to_integer(result["from"]),
45
-
to: String.to_integer(result["to"])
46
-
}
40
+
Regex.named_captures(~r/move (?<count>\d+) from (?<from>\d) to (?<to>\d)/, move)
41
+
|> Map.new(fn {k, v} -> {String.to_atom(k), String.to_integer(v)} end)
47
42
end)
48
43
49
44
crates =
···
60
55
end)
61
56
end)
62
57
|> Enum.zip()
63
-
|> Enum.map(&Tuple.to_list/1)
64
-
|> Enum.map(fn column -> Enum.drop_while(column, &is_nil/1) end)
58
+
|> Enum.map(fn column -> column |> Tuple.to_list() |> Enum.drop_while(&is_nil/1) end)
65
59
|> Enum.with_index(1)
66
60
|> Map.new(fn {v, k} -> {k, v} end)
67
61
```
···
91
85
92
86
Map.update!(columns, to, &(moved ++ &1))
93
87
end
88
+
89
+
def eval(crates, moves, reverse? \\ true) do
90
+
moves
91
+
|> Enum.reduce(crates, &Day05.move(&1, &2, reverse?))
92
+
|> Enum.sort()
93
+
|> Enum.map(fn {_, v} -> hd(v) end)
94
+
end
94
95
end
95
96
```
96
97
97
98
<!-- livebook:{"output":true} -->
98
99
99
100
```
100
-
{:module, Day05, <<70, 79, 82, 49, 0, 0, 10, ...>>, {:move, 3}}
101
+
{:module, Day05, <<70, 79, 82, 49, 0, 0, 13, ...>>, {:eval, 3}}
101
102
```
102
103
103
104
## Task 1
104
105
105
106
```elixir
106
-
moves
107
-
|> Enum.reduce(crates, &Day05.move/2)
108
-
|> Enum.sort()
109
-
|> Enum.map(fn {_, v} -> hd(v) end)
107
+
Day05.eval(crates, moves)
110
108
```
111
109
112
110
<!-- livebook:{"output":true} -->
···
118
116
## Task 2
119
117
120
118
```elixir
121
-
moves
122
-
|> Enum.reduce(crates, &Day05.move(&1, &2, false))
123
-
|> Enum.sort()
124
-
|> Enum.map(fn {_, v} -> hd(v) end)
119
+
Day05.eval(crates, moves, false)
125
120
```
126
121
127
122
<!-- livebook:{"output":true} -->