Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Advent of Code 2015 - Day 01

elixir/2015/day_01.livemd

Advent of Code 2015 - Day 01

Mix.install([
  {:kino_aoc, "~> 0.1.7"}
])

Introduction

2015 - Day 01

Puzzle

{:ok, puzzle_input} =
  KinoAOC.download_puzzle("2015", "1", System.fetch_env!("LB_AOC_SESSION"))

Parser

Code - Parser

defmodule Parser do
  def parse(input), do: String.codepoints(input)
end

Tests - Parser

ExUnit.start(autorun: false)

defmodule ParserTest do
  use ExUnit.Case, async: true
  import Parser

  @input "()()"
  @expected ["(", ")", "(", ")"]

  test "parse test" do
    actual = parse(@input)
    assert actual == @expected
  end
end

ExUnit.run()

Part One

Code - Part 1

defmodule PartOne do
  def solve(input) do
    IO.puts("--- Part One ---")
    IO.puts("Result: #{run(input)}")
  end

  def run(input) do
    input
    |> Parser.parse()
    |> Enum.reduce(0, fn step, score ->
      case step do
        "(" -> score + 1
        ")" -> score - 1
      end
    end)
  end
end

Tests - Part 1

ExUnit.start(autorun: false)

defmodule PartOneTest do
  use ExUnit.Case, async: true
  import PartOne

  @input "))((((("
  @expected 3

  test "part one" do
    actual = run(@input)
    assert actual == @expected
  end
end

ExUnit.run()

Solution - Part 1

PartOne.solve(puzzle_input)

Part Two

Code - Part 2

defmodule PartTwo do
  def solve(input) do
    IO.puts("--- Part Two ---")
    IO.puts("Result: #{run(input)}")
  end

  def run(input) do
    input
    |> Parser.parse()
    |> Enum.with_index(1)
    |> Enum.reduce_while(0, fn {step, floor}, curr_floor ->
      step = case step do
        "(" -> 1
        ")" -> -1
      end
      case curr_floor + step do
        -1 -> {:halt, floor}
        next_floor -> {:cont, next_floor}
      end
    end)
  end
end

Tests - Part 2

ExUnit.start(autorun: false)

defmodule PartTwoTest do
  use ExUnit.Case, async: true
  import PartTwo

  @input "()())"
  @expected 5

  test "part two" do
    actual = run(@input)
    assert actual == @expected
  end
end

ExUnit.run()

Solution - Part 2

PartTwo.solve(puzzle_input)