Created
December 5, 2020 15:38
-
-
Save ynonp/e503216808db7fdd17036a2ad16a10ce to your computer and use it in GitHub Desktop.
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
defmodule Seat do | |
defstruct min_row: 0, max_row: 127, min_col: 0, max_col: 7 | |
def from_string(str) do | |
str | |
|> String.graphemes | |
|> Enum.reduce(%Seat{}, &Day5.process_letter/2) | |
end | |
def from_tuple({row, col}) do | |
%Seat{ | |
min_row: row, | |
max_row: row, | |
min_col: col, | |
max_col: col, | |
} | |
end | |
end | |
defmodule Day5 do | |
def read_input do | |
File.read!("input/day5.txt") | |
|> String.split("\n", trim: true) | |
|> Enum.map(&Seat.from_string/1) | |
end | |
def process_letter(letter, seat) do | |
middle_row = (seat.max_row + seat.min_row) / 2 | |
middle_col = (seat.max_col + seat.min_col) / 2 | |
%Seat{ | |
min_row: (if letter == "B", do: ceil(middle_row), else: seat.min_row), | |
max_row: (if letter == "F", do: floor(middle_row), else: seat.max_row), | |
min_col: (if letter == "R", do: ceil(middle_col), else: seat.min_col), | |
max_col: (if letter == "L", do: floor(middle_col), else: seat.max_col) | |
} | |
end | |
def seat_id(seat) do | |
seat.min_row * 8 + seat.min_col | |
end | |
def part1 do | |
read_input() | |
|> Enum.map(&seat_id/1) | |
|> Enum.max | |
|> IO.inspect | |
end | |
def part2 do | |
marked_places = read_input() | |
|> Enum.map(fn seat -> { seat.max_row, seat.max_col } end) | |
|> MapSet.new | |
rows = marked_places | |
|> Enum.map(fn {row, _col} -> row end) | |
max_row = rows |> Enum.max | |
min_row = rows |> Enum.min | |
possible_places = for row <- min_row+1..max_row-1 , col <- 0..7 do | |
{ row, col } | |
end | |
|> MapSet.new | |
myplace = MapSet.difference(possible_places, marked_places) | |
|> Enum.at(0) | |
|> Seat.from_tuple | |
IO.inspect(seat_id(myplace)) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment