Powered by AppSignal & Oban Pro

Day 04

day04.livemd

Day 04

Mix.install([
  {:kino, "~> 0.14.2"}
])

IEx.Helpers.c("/Users/johnb/dev/2015adventOfCode/advent_of_code.ex")
alias AdventOfCode, as: AOC
alias Kino.Input
require Integer

# Note: when making the next template, something like this works well:
#   `cat day01.livemd | sed 's/01/02/' > day02.livemd`
#

Installation and Data

input_p1example = Kino.Input.textarea("Example Data")
input_p1puzzleInput = Kino.Input.textarea("Puzzle Input")
input_source_select =
  Kino.Input.select("Source", [{:example, "example"}, {:puzzle_input, "puzzle input"}])
p1data = fn ->
  (Kino.Input.read(input_source_select) == :example &&
     Kino.Input.read(input_p1example)) ||
    Kino.Input.read(input_p1puzzleInput)
end

Part 1

defmodule Day04 do
  
  def solve1(text) do
    Enum.reduce_while(0..99999999, 0, fn index, _acc -> 
      if :crypto.hash(:md5, "#{text}#{index}") |> Base.encode16() =~ ~r/^00000.*$/ do
        IO.puts("iwrupvqb#{index}")
        {:halt, index}
      else
        {:cont, nil}
      end
    end)
  end

  def solve2(text) do
    Enum.reduce_while(0..99999999, 0, fn index, _acc -> 
      if :crypto.hash(:md5, "#{text}#{index}") |> Base.encode16() =~ ~r/^000000.*$/ do
        IO.puts("iwrupvqb#{index}")
        {:halt, index}
      else
        if Integer.mod(index, 10_000) == 0 do
          IO.puts(index)
        end
        {:cont, nil}
      end
    end)
  end
end

# p1data.()
# |> Day04.solve1()
# |> IO.inspect(label: "\n*** Part 1 solution")
# 346386

p1data.()
|> Day04.solve2()
|> IO.inspect(label: "\n*** Part 2 solution (example: 11)")
# 9958218