Day4
Mix.install([
{:kino_aoc, git: "https://github.com/ljgago/kino_aoc"}
])
Section
{:ok, data} = KinoAOC.download_puzzle("2026", "4", System.fetch_env!("LB_AOC_SECRET"))
Solve
defmodule Day4 do
def task1(data) do
data
|> String.split("\n", trim: true)
|> solve()
end
def task2(data) do
data
|> String.split("\n", trim: true)
|> Enum.join()
|> List.wrap()
|> solve()
end
def solve(data) do
data
|> Enum.map(fn row -> row |> String.graphemes() |> find_min() end)
|> Enum.sum()
end
def find_min(row) do
Enum.reduce_while(1..length(row), false, fn n, _acc ->
case lazy_split(row, n) do
false ->
{:cont, false}
_patt ->
#length(patt) and 'n' are the same
{:halt, n}
end
end)
end
# lazy build chunks to save calculations on long strings
def lazy_split(row, n) do
row
|> Stream.chunk_every(n, n, Stream.cycle(["?"]))
|> Enum.reduce_while(nil, fn
chunk, nil -> {:cont, chunk}
chunk, patt ->
case chunks_match?(patt, chunk) do
{true, draft} -> {:cont, Enum.reverse(draft)}
{false, _} -> {:halt, false}
end
end)
end
def chunks_match?(a, b) do
[a, b]
|> Enum.zip()
|> Enum.reduce_while({true, []}, fn seg, {_check, acc} ->
{check, def} = char_match?(seg)
if check do
{:cont, {true, [def | acc]}}
else
{:halt, {false, [def | acc]}}
end
end)
end
def char_match?({"?", "?"}), do: {true, "?"}
def char_match?({"?", def}), do: {true, def}
def char_match?({def, "?"}), do: {true, def}
def char_match?({same, same}), do: {true, same}
def char_match?({_, _}), do: {false, :no_match}
end
tdata = """
rgbrgbrgbr
?rv
o??v???y
??bg?v??
??b?????
???
"""
tdata2 = """
rro??
?g
?g???
??r?????
??g?
??
yy?v?o
???v
b?g??
?y??v?or
????r?o
??
?????
?r??v?r
"""
Day4.task1(tdata) |> IO.inspect(label: "test 1")
Day4.task2(tdata2) |> IO.inspect(label: "test 2")
Day4.task1(data) |> IO.inspect(label: "task 1")
Day4.task2(data) |> IO.inspect(label: "task 2")