Created
December 11, 2023 05:53
-
-
Save rugyoga/558e8b36d20c159714068e373730a75e to your computer and use it in GitHub Desktop.
Advent of Code 2023 Day 11
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import AOC | |
aoc 2023, 11 do | |
def calculate(input, multiplier) do | |
grid = grid(input) |> Map.new() | |
{rows, cols} = grid |> Enum.unzip() |> elem(0) |> Enum.unzip() | |
row_max = rows |> Enum.max() | |
col_max = cols |> Enum.max() | |
blank_rows = 0..row_max |> Enum.filter(fn row -> Enum.all?(0..col_max, fn col -> grid[{row, col}] == "." end) end) | |
blank_cols = 0..col_max |> Enum.filter(fn col -> Enum.all?(0..row_max, fn row -> grid[{row, col}] == "." end) end) | |
galaxies = Enum.filter(grid, fn {_, char} -> char == "#" end) |> Enum.unzip() |> elem(0) | |
for i <- 1..Enum.count(galaxies), j <- 1..i, j < i do | |
distance(Enum.at(galaxies, i-1), Enum.at(galaxies, j-1), blank_rows, blank_cols, multiplier) | |
end |> Enum.sum() | |
end | |
def p1(input) do | |
calculate(input, 2) | |
end | |
def p2(input) do | |
calculate(input, 1_000_000) | |
end | |
def distance({a, b}, {c, d}, blank_rows, blank_cols, multiplier) do | |
[lo_row, hi_row] = [a, c] |> Enum.sort() | |
[lo_col, hi_col] = [b, d] |> Enum.sort() | |
[blank_rows |> Enum.count(fn row -> lo_row <= row and row <= hi_row end) |> Kernel.*(multiplier-1), | |
blank_cols |> Enum.count(fn col -> lo_col <= col and col <= hi_col end) |> Kernel.*(multiplier-1), | |
hi_row - lo_row, | |
hi_col - lo_col] |> Enum.sum() | |
end | |
def grid(input) do | |
input | |
|> String.split("\n", trim: true) | |
|> Enum.with_index | |
|> Enum.flat_map( | |
fn {line, row} -> | |
line | |
|> String.split("", trim: true) | |
|> Enum.with_index | |
|> Enum.map(fn {char, col} -> {{row, col}, char} end) | |
end) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment