2019-12-06 19:06:49 +01:00
|
|
|
use std::fmt::Write;
|
|
|
|
|
2019-12-03 15:06:28 +01:00
|
|
|
use md5::{Digest, Md5};
|
|
|
|
|
2020-12-14 20:04:47 +01:00
|
|
|
use anyhow::{anyhow, Result};
|
2019-12-03 15:06:28 +01:00
|
|
|
|
|
|
|
const INPUT: &str = include_str!("../input/day04.txt");
|
|
|
|
|
2019-12-06 19:06:49 +01:00
|
|
|
pub fn run() -> Result<String> {
|
|
|
|
let mut res = String::with_capacity(128);
|
|
|
|
|
|
|
|
writeln!(res, "part 1: {}", part1(INPUT)?)?;
|
|
|
|
writeln!(res, "part 2: {}", part2(INPUT)?)?;
|
2019-12-03 15:06:28 +01:00
|
|
|
|
2019-12-06 19:06:49 +01:00
|
|
|
Ok(res)
|
2019-12-03 15:06:28 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
fn part1(input: &str) -> Result<u64> {
|
|
|
|
let input = input.trim_end();
|
2019-12-03 15:22:25 +01:00
|
|
|
let mut content = String::from(input);
|
2019-12-03 15:06:28 +01:00
|
|
|
|
|
|
|
let mut hasher = Md5::new();
|
|
|
|
|
|
|
|
for i in 0.. {
|
2019-12-03 15:22:25 +01:00
|
|
|
content.truncate(input.len());
|
2019-12-05 16:35:39 +01:00
|
|
|
content.push_str(&i.to_string());
|
2019-12-03 15:06:28 +01:00
|
|
|
|
2019-12-03 15:22:25 +01:00
|
|
|
hasher.input(&content);
|
|
|
|
let res = hasher.result_reset();
|
2019-12-05 16:35:39 +01:00
|
|
|
if res[..2] == [0, 0] && res[2] <= 0x0f {
|
2019-12-03 15:06:28 +01:00
|
|
|
return Ok(i);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-14 20:04:47 +01:00
|
|
|
Err(anyhow!("couldn't find a suitable number"))
|
2019-12-03 15:06:28 +01:00
|
|
|
}
|
|
|
|
|
2019-12-03 15:40:50 +01:00
|
|
|
fn part2(input: &str) -> Result<u64> {
|
|
|
|
let input = input.trim_end();
|
|
|
|
let mut content = String::from(input);
|
|
|
|
|
|
|
|
let mut hasher = Md5::new();
|
|
|
|
|
|
|
|
for i in 0.. {
|
|
|
|
content.truncate(input.len());
|
2019-12-05 16:35:39 +01:00
|
|
|
content.push_str(&i.to_string());
|
2019-12-03 15:40:50 +01:00
|
|
|
|
|
|
|
hasher.input(&content);
|
|
|
|
let res = hasher.result_reset();
|
2019-12-05 16:35:39 +01:00
|
|
|
if res[..3] == [0, 0, 0] {
|
2019-12-03 15:40:50 +01:00
|
|
|
return Ok(i);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-14 20:04:47 +01:00
|
|
|
Err(anyhow!("couldn't find a suitable number"))
|
2019-12-03 15:40:50 +01:00
|
|
|
}
|
|
|
|
|
2019-12-03 15:06:28 +01:00
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
#[ignore] // takes too long!
|
|
|
|
fn part1_provided() {
|
|
|
|
assert_eq!(part1("abcdef").unwrap(), 609043);
|
|
|
|
assert_eq!(part1("pqrstuv").unwrap(), 1048970);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
#[ignore] // takes too long!
|
|
|
|
fn part1_real() {
|
|
|
|
assert_eq!(part1(INPUT).unwrap(), 282749);
|
|
|
|
}
|
2019-12-03 15:40:50 +01:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
#[ignore] // takes too long!
|
|
|
|
fn part2_real() {
|
|
|
|
assert_eq!(part2(INPUT).unwrap(), 9962624);
|
|
|
|
}
|
2019-12-03 15:06:28 +01:00
|
|
|
}
|