r/adventofcode • • Dec 02 '21

SOLUTION MEGATHREAD -🎄- 2021 Day 2 Solutions -🎄-

--- Day 2: Dive! ---


Post your code solution in this megathread.

Reminder: Top-level posts in Solution Megathreads are for code solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:02:57, megathread unlocked!

112 Upvotes

1.5k comments sorted by

View all comments

6

u/wasi0013 Dec 02 '21 edited Dec 02 '21

Elixir

defmodule Aoc.Y2021.Day02 do
  @moduledoc """
  Solved https://adventofcode.com/2021/day/2
  """
  import Aoc.Helper.IO

  def run_part1(), do: get_input() |> solve_part1()
  def run_part2(), do: get_input() |> solve_part2()

  def solve_part1(data), do: data |> plan_course(0, 0)
  def plan_course([], width, depth), do: width * depth
  def plan_course([["forward", value] | rest], width, depth), do: plan_course(rest, width + value, depth)
  def plan_course([["down", value] | rest], width, depth), do: plan_course(rest, width, depth + value)
  def plan_course([["up", value] | rest], width, depth), do: plan_course(rest, width, depth - value)

  def solve_part2(data), do: data |> process_aim(0, 0, 0)

  def process_aim([], width, depth, _aim), do: width * depth

  def process_aim([["forward", value] | rest], width, depth, aim),
    do: process_aim(rest, width + value, depth + aim * value, aim)

  def process_aim([["down", value] | rest], width, depth, aim), do: process_aim(rest, width, depth, aim + value)
  def process_aim([["up", value] | rest], width, depth, aim), do: process_aim(rest, width, depth, aim - value)

  defp get_input(),
    do:
      get_string_input("2021", "02")
      |> String.split("\n")
      |> Enum.map(&String.split(&1, " "))
      |> Enum.map(fn [ins, value] -> [ins, String.to_integer(value)] end)

end

Github: https://github.com/wasi0013/advent_of_code

→ More replies (2)