Day 4
This commit is contained in:
parent
c46d8eb680
commit
e7408ad2ff
|
@ -0,0 +1,55 @@
|
|||
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
|
Loading…
Reference in New Issue