Skip to content

Commit bc8b58e

Browse files
committed
Refactor calc_load and tilt_n_cycle functions
1 parent afc31fa commit bc8b58e

File tree

1 file changed

+9
-15
lines changed

1 file changed

+9
-15
lines changed

14/sol.exs

+9-15
Original file line numberDiff line numberDiff line change
@@ -54,27 +54,21 @@ defmodule Day14 do
5454
rotate(tails, acc ++ [Enum.reverse(heads)])
5555
end
5656

57-
def calc_load([], _, acc), do: acc
58-
def calc_load(["O" | t], i, acc), do: calc_load(t, i + 1, acc + i)
59-
def calc_load([_ | t], i, acc), do: calc_load(t, i + 1, acc)
60-
def calc_load(l), do: calc_load(l, 1, 0)
57+
def calc_load(l) do
58+
Enum.with_index(l)
59+
|> Enum.reduce(0, fn {x, i}, acc -> if(x == "O", do: acc + i + 1, else: acc) end)
60+
end
61+
6162
def calc_all_loads(ll), do: Enum.map(ll, &calc_load/1) |> Enum.sum()
6263

63-
def tilt_1_cycle(ll) do
64-
ll |> tilt_and_rotate() |> tilt_and_rotate() |> tilt_and_rotate() |> tilt_and_rotate()
65-
end
64+
def tilt_1_cycle(ll), do: Enum.reduce(1..4, ll, fn _, acc -> tilt_and_rotate(acc) end)
6665

67-
def tilt_n_cycle(ll, n), do: tilt_n_cycle(ll, n, %{n: n})
66+
def tilt_n_cycle(ll, n), do: tilt_n_cycle(ll, n, %{})
6867
def tilt_n_cycle(ll, 0, _), do: ll
6968

7069
def tilt_n_cycle(ll, m, memo) do
71-
new_m =
72-
case is_map_key(memo, ll) do
73-
true -> Integer.mod(m, memo[ll] - m) - 1
74-
false -> m - 1
75-
end
76-
77-
tilt_n_cycle(ll |> tilt_1_cycle(), new_m, Map.put(memo, ll, m))
70+
new_m = if Map.has_key?(memo, ll), do: Integer.mod(m, memo[ll] - m), else: m
71+
tilt_n_cycle(tilt_1_cycle(ll), new_m - 1, Map.put(memo, ll, m))
7872
end
7973
end
8074

0 commit comments

Comments
 (0)