04
Section
example = """
MMMSXXMASM
MSAMXMSMSA
AMXSXMAAMM
MSAMASMSMX
XMASAMXAMM
XXAMMXXAMA
SMSMSASXSS
SAXAMASAAA
MAMMMXMMMM
MXMXAXMASX
"""
defmodule Day04 do
def into_map(input, whilte_list) do
for {row, y} <- input |> String.split("\n", trim: true) |> Enum.with_index(),
{c, x} <- row |> String.split("", trim: true) |> Enum.with_index(),
c in whilte_list,
into: %{} do
{{x, y}, c}
end
end
def part1(input) do
map = into_map(input, ["X", "M", "A", "S"])
for {start, "X"} <- map,
xadd <- -1..1,
yadd <- -1..1,
xadd == yadd != 0,
xmas(map, start, xadd, yadd),
reduce: 0 do
acc -> acc + 1
end
end
def xmas(map, {x, y}, xadd, yadd) do
Map.get(map, {x + xadd, y + yadd}) == "M" &&
Map.get(map, {x + xadd * 2, y + yadd * 2}) == "A" &&
Map.get(map, {x + xadd * 3, y + yadd * 3}) == "S"
end
def part2(input) do
map = into_map(input, ["M", "A", "S"])
for {start, "A"} <- map,
xadd <- [1, -1],
yadd <- [1, -1],
x_mas(map, start, xadd, yadd) do
start
end
|> Enum.frequencies()
|> Enum.count(&(elem(&1, 1) == 2))
end
def x_mas(map, {x, y}, xadd, yadd) do
Map.get(map, {x + xadd, y + yadd}) == "M" && Map.get(map, {x - xadd, y - yadd}) == "S"
end
end
Day04.part1(example)
Day04.part2(example)