AoC19/lib/day4/day4.ex

56 lines
1.1 KiB
Elixir
Raw Permalink Normal View History

2019-12-04 15:23:50 +00:00
defmodule Day4 do
def part1 do
158_126..624_574
|> Enum.reduce(0, fn n, acc ->
if test1(n) do
IO.inspect(n)
acc + 1
else
acc
end
end)
end
def part2 do
158_126..624_574
|> Enum.reduce(0, fn n, acc ->
if test2(n) do
IO.inspect(n)
acc + 1
else
acc
end
end)
end
def test1(n) do
cl = Integer.to_charlist(n)
chunks = chunk_by_digits(cl)
chunks == Enum.sort(chunks) && Enum.any?(chunks, &(length(&1) >= 2))
end
def test2(n) do
cl = Integer.to_charlist(n)
chunks = chunk_by_digits(cl)
chunks == Enum.sort(chunks) && Enum.any?(chunks, &(length(&1) == 2))
end
def chunk_by_digits(cl, current_chunk \\ [], chunks \\ [])
def chunk_by_digits([a, b | rest], current_chunk, chunks) do
rest = [b | rest]
if a == b do
chunk_by_digits(rest, [a | current_chunk], chunks)
else
chunk_by_digits(rest, [], [Enum.reverse([a | current_chunk]) | chunks])
end
end
def chunk_by_digits([a | []], current_chunk, chunks) do
Enum.reverse([Enum.reverse([a | current_chunk]) | chunks])
end
end