diff --git a/README.md b/README.md index 42dfb60..666324f 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ My (attempted) solutions to [Advent of Code 2020](https://adventofcode.com/2020) in Elixir. -image +image ## Strategy diff --git a/day1/README b/day1/README index 1f97bca..dd58507 100644 --- a/day1/README +++ b/day1/README @@ -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. + diff --git a/day1/day1part2.exs b/day1/day1part2.exs new file mode 100644 index 0000000..ad0a73d --- /dev/null +++ b/day1/day1part2.exs @@ -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()