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

Day 4: The Ideal Stocking Stuffer

day04.livemd

Day 4: The Ideal Stocking Stuffer

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

Input

input = Kino.Input.textarea("Please paste your input:")

Part 1

Santa needs help mining some AdventCoins (very similar to bitcoins) to use as gifts for all the economically forward-thinking little girls and boys.

To do this, he needs to find MD5 hashes which, in hexadecimal, start with at least five zeroes. The input to the MD5 hash is some secret key (your puzzle input, given below) followed by a number in decimal. To mine AdventCoins, you must find Santa the lowest positive number (no leading zeroes: 1, 2, 3, …) that produces such a hash.

For example:

  • If your secret key is abcdef, the answer is 609043, because the MD5 hash of abcdef609043 starts with five zeroes (000001dbbfa...), and it is the lowest such number to do so.
  • If your secret key is pqrstuv, the lowest number it combines with to make an MD5 hash starting with five zeroes is 1048970; that is, the MD5 hash of pqrstuv1048970 looks like 000006136ef....
defmodule John do
  def ripper(key, zeros \\ 5), do: brute(key, 1, zeros * 4)

  # check if calculated md5 hash starts with a given number of zero bits,
  # otherwise add 1 to n and check again, until we nail it
  defp brute(key, n, bits) do
    hash = :crypto.hash(:md5, "#{key}#{n}")

    case hash do
      <<0::size(bits), _::bitstring>> -> n
      _ -> brute(key, n + 1, bits)
    end
  end
end

input
|> Kino.Input.read()
|> John.ripper()

Part 2

Now find one that starts with six zeroes.

input
|> Kino.Input.read()
|> John.ripper(6)