Created
December 3, 2020 16:04
-
-
Save ynonp/875412c2aad671ce1d2856c5a82e590a 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 Day3 do | |
def read_input do | |
File.read!("input/day3.txt") | |
|> String.split("\n", trim: true) | |
|> Enum.map(&String.graphemes/1) | |
|> Enum.map(&Enum.with_index/1) | |
|> Enum.with_index | |
|> Enum.flat_map(fn {line, row} -> Enum.map(line, fn {el, col} -> {{row, col}, (if el == "#", do: 1, else: 0) } end) end) | |
|> Enum.into(%{}) | |
end | |
def slope(dr, dc, column_count) do | |
Stream.iterate({0, 0}, fn {row, col} -> {row + dr, rem(col + dc, column_count)} end) | |
end | |
def part1 do | |
data = read_input() | |
column_count = (data |> Map.keys |> Enum.map(fn {_row, col} -> col end) |> Enum.max) + 1 | |
row_count = (data |> Map.keys |> Enum.map(fn {row, _col} -> row end) |> Enum.max) + 1 | |
slope = slope(1, 3, column_count) |> Stream.take_while(fn {row, _col} -> row < row_count end) |> Enum.to_list | |
data |> Map.take(slope) |> Map.values |> Enum.sum |> IO.inspect | |
end | |
def part2 do | |
data = read_input() | |
column_count = (data |> Map.keys |> Enum.map(fn {_row, col} -> col end) |> Enum.max) + 1 | |
row_count = (data |> Map.keys |> Enum.map(fn {row, _col} -> row end) |> Enum.max) + 1 | |
slopes = [ | |
{1, 1}, | |
{1, 3}, | |
{1, 5}, | |
{1, 7}, | |
{2, 1}] | |
|> Enum.map(fn {dr, dc} -> slope(dr, dc, column_count) end) | |
|> Enum.map(fn slope -> slope |> Stream.take_while(fn {row, _col} -> row < row_count end) |> Enum.to_list end) | |
slopes | |
|> Enum.map(fn slope -> (data |> Map.take(slope) |> Map.values |> Enum.sum) end) | |
|> Enum.reduce(&(&1 * &2)) | |
|> IO.inspect | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment