--- Day 4: The Ideal Stocking Stuffer ---

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

Rust Solution

use md5::*;
use rayon::prelude::*;
use rustgym_util::*;
use std::fmt::Write;
use std::io::*;

pub fn solve(reader: &mut dyn BufRead, writer: &mut dyn Write) {
    let mut it = reader.lines().map(|l| l.unwrap());
    let line = it.next().unwrap();

    let res1 = search(1000000, &line, "00000");
    let res2 = search(10000000, &line, "000000");
    writeln!(writer, "{}", res1).unwrap();
    writeln!(writer, "{}", res2).unwrap();
}

fn search(max: usize, line: &str, prefix: &str) -> usize {
    (0..max)
        .into_par_iter()
        .position_first(|x| {
            let s = format!("{}{}", line, x);
            let digest = format!("{:?}", compute(s));
            digest.starts_with(prefix)
        })
        .unwrap()
}

advent_of_code_ignore!(test, "input.txt", "output.txt");

Having problems with this solution? Click here to submit an issue on github.