AdventOfCode/2024/day4.exs

126 lines
3.2 KiB
Elixir
Raw Normal View History

2024-12-04 13:40:31 +00:00
#!/usr/bin/env elixir
defmodule Day4 do
def part1(grid) do
n = :array.size(grid)
horizontal =
for y <- 0..(n - 1), x <- 0..(n - 4), reduce: 0 do
count ->
for x_offset <- 0..(4 - 1), into: "" do
:array.get(x + x_offset, :array.get(y, grid))
end
|> consider(count)
end
vertical =
for y <- 0..(n - 4), x <- 0..(n - 1), reduce: 0 do
count ->
for y_offset <- 0..(4 - 1), into: "" do
:array.get(x, :array.get(y + y_offset, grid))
end
|> consider(count)
end
diagonal1 =
for y <- 0..(n - 4), x <- 0..(n - 4), reduce: 0 do
count ->
for offset <- 0..(4 - 1), into: "" do
:array.get(x + offset, :array.get(y + offset, grid))
end
|> consider(count)
end
diagonal2 =
for y <- 0..(n - 4), x <- (n - 1)..(4 - 1), reduce: 0 do
count ->
for offset <- 0..(4 - 1), into: "" do
:array.get(x - offset, :array.get(y + offset, grid))
end
|> consider(count)
end
horizontal + vertical + diagonal1 + diagonal2
end
def consider("XMAS", count), do: count + 1
def consider("SAMX", count), do: count + 1
def consider(_, count), do: count
def part2(grid) do
n = :array.size(grid)
for y <- 0..(n - 3), x <- 0..(n - 3), reduce: 0 do
count ->
diagonal1 =
for offset <- 0..2, into: "" do
:array.get(x + offset, :array.get(y + offset, grid))
end
diagonal2 =
for offset <- 0..2, into: "" do
:array.get(x + 2 - offset, :array.get(y + offset, grid))
end
if diagonal1 in ["MAS", "SAM"] and diagonal2 in ["MAS", "SAM"] do
count + 1
else
count
end
end
end
def input do
with [input_filename] <- System.argv(),
{:ok, input} <- File.read(input_filename) do
for <<char::binary-1 <- input>>, reduce: {:array.new(), :array.new(), 0, 0} do
{rows, cols, x, y} ->
case char do
"\n" ->
rows = :array.set(y, cols, rows)
cols = :array.new()
{rows, cols, 0, y + 1}
char ->
cols = :array.set(x, char, cols)
{rows, cols, x + 1, y}
end
end
|> elem(0)
else
_ -> :error
end
end
#######################
# HERE BE BOILERPLATE #
#######################
def run do
case input() do
:error -> print_usage()
input -> run_parts_with_timer(input)
end
end
defp run_parts_with_timer(input) do
run_with_timer(1, fn -> part1(input) end)
run_with_timer(2, fn -> part2(input) end)
end
defp run_with_timer(part, fun) do
{time, result} = :timer.tc(fun)
IO.puts("Part #{part} (completed in #{format_time(time)}):\n")
IO.puts("#{inspect(result)}\n")
end
defp format_time(μsec) when μsec < 1_000, do: "#{μsec}μs"
defp format_time(μsec) when μsec < 1_000_000, do: "#{μsec / 1000}ms"
defp format_time(μsec), do: "#{μsec / 1_000_000}s"
defp print_usage do
IO.puts("Usage: elixir day4.exs input_filename")
end
end
Day4.run()