Skip to content

Instantly share code, notes, and snippets.

@sasa1977
Created December 2, 2017 13:44
Show Gist options
  • Save sasa1977/028a13921489f16a41f8c346578c4b5f to your computer and use it in GitHub Desktop.
Save sasa1977/028a13921489f16a41f8c346578c4b5f to your computer and use it in GitHub Desktop.
# http://adventofcode.com/2017/day/2
defmodule Day2 do
def checksum1(rows), do:
rows
|> Enum.map(&row_checksum1/1)
|> Enum.sum()
defp row_checksum1(row) do
{min, max} =
Enum.reduce(
row,
{nil, nil},
fn
number, {nil, nil} -> {number, number}
number, {min, max} when number < min -> {number, max}
number, {min, max} when number > max -> {min, number}
_number, acc -> acc
end
)
(max || 0) - (min || 0)
end
def checksum2(rows), do:
rows
|> Enum.map(&row_checksum2/1)
|> Enum.sum()
defp row_checksum2(row) do
[{x, y}] =
row
|> ordered_permutations()
|> Stream.map(fn {x, y} -> {max(x, y), min(x, y)} end)
|> Enum.filter(fn {x, y} -> rem(x, y) == 0 end)
div(x, y)
end
defp ordered_permutations(row), do:
Stream.resource(
fn -> row end,
fn
[] -> {:halt, nil}
[head | tail] -> {Stream.map(tail, &{head, &1}), tail}
end,
fn nil -> :ok end
)
def read(), do:
"input.txt"
|> File.read!()
|> String.trim()
|> String.split("\n")
|> Enum.map(&(&1 |> String.trim() |> String.split() |> Enum.map(fn x -> String.to_integer(x) end)))
end
Day2.read() |> Day2.checksum1() |> IO.inspect
Day2.read() |> Day2.checksum2() |> IO.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment