Skip to content

Instantly share code, notes, and snippets.

@onebree

onebree/day04.md Secret

Last active December 15, 2015 13:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save onebree/96c02a6bb2a4c55b615a to your computer and use it in GitHub Desktop.
Save onebree/96c02a6bb2a4c55b615a to your computer and use it in GitHub Desktop.
advent of code - day 4

Day 4: The Ideal Stocking Stuffer

Part One

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....

Part Two

Now find one that starts with six zeroes.

require 'digest'
def md5_hex(input, value)
Digest::MD5.hexdigest("#{input}#{value}")
end
def find_first_num(input, z)
(1..Float::INFINITY).find { |x| md5_hex(input, x)[0...z] == '0' * z }
end
input = File.read('input').strip
puts "First number to generate an md5 hash with 5 leading zeroes: #{find_first_num(input, 5)}"
puts "First number to generate an md5 hash with 6 leading zeroes: #{find_first_num(input, 6)}"
iwrupvqb
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment