Advent of Code - Day 6
Part 1
input = File.read!("inputs/day6.txt")
input
|> String.graphemes()
|> Enum.with_index(1)
|> Enum.reduce_while(
[],
fn {c, i}, l ->
case Enum.uniq([c | l]) do
new_l when length(new_l) == 4 -> {:halt, i}
_ -> {:cont, Enum.take([c | l], 3)}
end
end
)
(input
|> String.to_charlist()
|> Stream.chunk_every(4, 1, :discard)
|> Enum.find_index(&(&1 |> Enum.uniq() |> length == 4))) + 4
Part2
input
|> String.graphemes()
|> Enum.with_index(1)
|> Enum.reduce_while(
[],
fn {c, i}, l ->
case Enum.uniq([c | l]) do
new_l when length(new_l) == 14 -> {:halt, i}
_ -> {:cont, Enum.take([c | l], 13)}
end
end
)
(input
|> String.to_charlist()
|> Stream.chunk_every(14, 1, :discard)
|> Enum.find_index(&(&1 |> Enum.uniq() |> length == 14))) + 14
input
|> String.to_charlist()
|> Stream.chunk_every(14, 1, :discard)
|> Stream.with_index(15)
|> Stream.take_while(fn {l, _i} -> l |> Enum.uniq() |> length() != 14 end)
|> Stream.take(-1)
|> Enum.to_list()
|> hd()
|> elem(1)
defmodule Day6 do
# patternmatching fun!
# l = the list of chars, p = position where we are in the list
# s = the size of consecutive non-repetitive chars we're looking for
def find_marker(l, p, s), do: find_marker(l, p, s, length(Enum.uniq(Enum.take(l, s))))
def find_marker(_, p, s, s), do: p + s
def find_marker(l, p, s, _), do: find_marker(tl(l), p + 1, s)
end
input
|> String.to_charlist()
|> Day6.find_marker(0, 4)