Day 1 Part 2

This commit is contained in:
Adam Millerchip 2020-12-01 14:36:44 +09:00
parent ae06003210
commit 3d2d6e3a39
3 changed files with 47 additions and 1 deletions

View File

@ -2,7 +2,7 @@
My (attempted) solutions to [Advent of Code 2020](https://adventofcode.com/2020) in Elixir.
<img width="967" alt="image" src="https://user-images.githubusercontent.com/498229/100191430-6fc5be80-2f33-11eb-8a96-21d87c503c74.png">
<img width="976" alt="image" src="https://user-images.githubusercontent.com/498229/100701084-45b44680-33e2-11eb-9fb9-11c6161a49ef.png">
## Strategy

View File

@ -1,6 +1,25 @@
Day 1 Notes
------
Part1:
------
$ elixir day1part1.exs
618 x 1402 = 866436
Thoughts:
Avoid iterating seen elements by consuming the list, and comparing each list element only to the remaining
elements.
------
Part2:
------
$ elixir day1part2.exs
547 x 545 x 928 = 276650720
Thoughts:
Use a comprehension over two versions of the remaining list to efficiently compare the three items.

27
day1/day1part2.exs Normal file
View File

@ -0,0 +1,27 @@
defmodule Day1Part2 do
def run do
{a, b, c} =
File.read!("input")
|> String.trim()
|> String.split("\n")
|> Enum.map(&String.to_integer/1)
|> find_2020()
IO.puts("#{a} x #{b} x #{c} = #{a * b * c}")
end
def find_2020([current | rest]) do
pair =
for i <- rest, j <- rest do
if current + i + j == 2020, do: {i, j}, else: nil
end
|> Enum.find(&match?({_, _}, &1))
case pair do
{a, b} -> {a, b, current}
nil -> find_2020(rest)
end
end
end
Day1Part2.run()