solve 2022 day 7 pt 1
This commit is contained in:
parent
12ce2934ea
commit
fc2c674f0f
3 changed files with 53 additions and 2 deletions
|
@ -3,7 +3,7 @@
|
|||
| S | M | T | W | T | F | S |
|
||||
| :-: | :-: | :-: | :-: | :-: | :-: | :--: |
|
||||
| | | | | [1] | [2] | [3] |
|
||||
| [4] | [5] | [6] | 7 | 8 | 9 | 10 |
|
||||
| [4] | [5] | [6] | [7] | 8 | 9 | 10 |
|
||||
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
|
||||
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
|
||||
| 24 | | | | | | |
|
||||
|
@ -14,3 +14,4 @@
|
|||
[4]: ./haskell/src/Aoc/Day4.hs
|
||||
[5]: ./haskell/src/Aoc/Day5.hs
|
||||
[6]: ./haskell/src/Aoc/Day6.hs
|
||||
[7]: ./elixir/lib/2022/7.ex
|
||||
|
|
50
2022/elixir/lib/2022/7.ex
Normal file
50
2022/elixir/lib/2022/7.ex
Normal file
|
@ -0,0 +1,50 @@
|
|||
import AOC
|
||||
|
||||
aoc 2022, 7 do
|
||||
def p1(input) do
|
||||
{sized_dirs, _} = input
|
||||
|> String.split("\n")
|
||||
|> Enum.flat_map(&transform_input_line/1)
|
||||
|> Enum.reduce({nil, %{}}, &update_state/2)
|
||||
|> then(fn {_, fs} -> fs end)
|
||||
|> calculate_dir_size("/")
|
||||
|
||||
sized_dirs
|
||||
|> Enum.map(&elem(&1, 1))
|
||||
|> Enum.reject(& &1 > 100_000)
|
||||
|> Enum.sum()
|
||||
end
|
||||
|
||||
def p2(_input) do
|
||||
end
|
||||
|
||||
defp transform_input_line("$ cd " <> path), do: [{:cd, path}]
|
||||
defp transform_input_line("$ ls" <> _), do: []
|
||||
defp transform_input_line("dir " <> d), do: [{:d, d}]
|
||||
defp transform_input_line(file) do
|
||||
[size_s, f] = String.split(file, " ")
|
||||
[{:f, f, String.to_integer(size_s)}]
|
||||
end
|
||||
|
||||
defp update_state({:cd, path}, {cwd, fs}), do: {cd(cwd, path), fs}
|
||||
defp update_state({:d, d}, {cwd, fs}), do: {cwd, Map.update(fs, cwd, [Path.join(cwd, d)], & [Path.join(cwd, d) | &1])}
|
||||
defp update_state({:f, _, f}, {cwd, fs}), do: {cwd, Map.update(fs, cwd, [f], & [f | &1])}
|
||||
defp update_state(_, s), do: s
|
||||
|
||||
defp cd(_cwd, "/" <> _ = path), do: path
|
||||
defp cd(cwd, path), do: Path.join(cwd, path) |> Path.expand()
|
||||
|
||||
defp calculate_dir_size(fs, path) do
|
||||
{updated_fs, total} = for item <- fs[path], reduce: {fs, 0} do
|
||||
{acc_fs, sum} ->
|
||||
case item do
|
||||
f when is_integer(f) -> {acc_fs, sum + f}
|
||||
d when is_binary(d) ->
|
||||
{acc_fs_, v} = calculate_dir_size(acc_fs, d)
|
||||
{acc_fs_, v + sum}
|
||||
end
|
||||
end
|
||||
{Map.put(updated_fs, path, total), total}
|
||||
end
|
||||
|
||||
end
|
|
@ -13,7 +13,7 @@
|
|||
1. 2019
|
||||
1. [2020] **17/50** 🌟
|
||||
1. [2021] **43/50** 🌟
|
||||
1. [2022] **12/50** 🌟
|
||||
1. [2022] **13/50** 🌟
|
||||
|
||||
[2015]: ./2015
|
||||
[2017]: ./2017
|
||||
|
|
Loading…
Reference in a new issue