Created
December 6, 2020 02:44
-
-
Save neenjaw/9b009671e8ee18ae6d32bd71ae69999f to your computer and use it in GitHub Desktop.
Elixir variation
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 AdventOfCode.Day05 do | |
import Bitwise, only: [<<<: 2] | |
def walk(line) do | |
line | |
|> String.reverse() | |
|> do_walk() | |
end | |
def do_walk(ticket, sum \\ 0, place \\ 0) | |
def do_walk(<<>>, sum, _), do: sum | |
# ?F and ?L are equal to binary 0 | |
def do_walk(<<l, rest::binary>>, sum, place) when l in 'FL' do | |
do_walk(rest, sum, place + 1) | |
end | |
# ?B and ?R are equal to binary 1 | |
def do_walk(<<l, rest::binary>>, sum, place) when l in 'BR' do | |
do_walk(rest, sum + (1 <<< place), place + 1) | |
end | |
def part1(args) do | |
args | |
|> Stream.map(&walk/1) | |
|> Enum.max() | |
end | |
def part2(args) do | |
# O(n log n) | |
# args | |
# |> Stream.map(&walk/1) | |
# |> Enum.sort(:asc) | |
# |> Enum.reduce_while(nil, fn | |
# n, nil -> {:cont, n} | |
# n, last when n == last + 1 -> {:cont, n} | |
# n, _ -> {:halt, {:ok, n - 1}} | |
# end) | |
# |> (fn | |
# {:ok, n} -> n | |
# _ -> nil | |
# end).() | |
# O(n) | |
{sum, min, max, count} = | |
args | |
|> Stream.map(&walk/1) | |
|> Enum.reduce({0, 2 <<< 9, 0, 0}, fn n, {sum, min, max, count} -> | |
sum = sum + n | |
min = Enum.min([min, n]) | |
max = Enum.max([max, n]) | |
count = count + 1 | |
{sum, min, max, count} | |
end) | |
expected_sum = ((count + 1) * (min + max) / 2) |> trunc() | |
expected_sum - sum | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment