Advent of Code 2020 in Elixir - Day 1

Advent of Code 2020 in Elixir - Day 1

Receipt Repair

As usual AOC tries to lull you into a false sense of confidence but starting with a fairly easy puzzle on day 1.

defmodule Aoc2020.Day1 do
  @moduledoc "Receipt Repair"

  def run(), do: part_1()

  def part_1(), do: parse_input() |> pair_sum()
  def part_2(), do: parse_input() |> triplet_sum()

  def parse_input() do
    File.read!("priv/inputs/2020/day1.txt")
    |> String.trim()
    |> String.split("\n")
    |> Enum.map(&String.to_integer/1)
  end

  # part 1
  def pair_sum(expenses) do
    expenses
    |> combine_every_pair()
    |> Enum.find(fn [x, y] -> x + y == 2020 end)
    |> (fn [x, y] -> x * y end).()
  end

  def combine_every_pair(expenses) do
    for x <- expenses, y <- expenses, x != y, do: [x, y]
  end

  # part 2 
  def triplet_sum(expenses) do
    expenses
    |> combine_every_triplet()
    |> Enum.find(fn [x, y, z] -> x + y + z == 2020 end)
    |> (fn [x, y, z] -> x * y * z end).()
  end

  def combine_every_triplet(expenses) do
    for x <- expenses, y <- expenses, z <- expenses, do: [x, y, z]
  end
end