From 92d5b896237ea3ff3bc3dd0db0df7da396d73399 Mon Sep 17 00:00:00 2001 From: YK Date: Tue, 19 Nov 2024 23:53:38 +0300 Subject: [PATCH] solution: day 5 + deps --- Cargo.lock | 7 +++++ Cargo.toml | 1 + src/days.rs | 2 +- src/days/d5.rs | 74 ++++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 83 insertions(+), 1 deletion(-) create mode 100644 src/days/d5.rs diff --git a/Cargo.lock b/Cargo.lock index 252f627..3c79a9a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -14,6 +14,7 @@ version = "0.1.0" dependencies = [ "anyhow", "itertools", + "md5", ] [[package]] @@ -30,3 +31,9 @@ checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" dependencies = [ "either", ] + +[[package]] +name = "md5" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771" diff --git a/Cargo.toml b/Cargo.toml index bae03a5..4a26cba 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,3 +6,4 @@ edition = "2021" [dependencies] anyhow = "1.0.93" itertools = "0.13.0" +md5 = "0.7.0" diff --git a/src/days.rs b/src/days.rs index 21b6c99..4436c45 100644 --- a/src/days.rs +++ b/src/days.rs @@ -2,7 +2,7 @@ pub mod d1; pub mod d2; pub mod d3; pub mod d4; -// pub mod d5; +pub mod d5; // pub mod d6; // pub mod d7; // pub mod d8; diff --git a/src/days/d5.rs b/src/days/d5.rs new file mode 100644 index 0000000..ee79ed1 --- /dev/null +++ b/src/days/d5.rs @@ -0,0 +1,74 @@ +use crate::prelude::*; + +pub type I = &'static str; +pub type O = String; + +fn _silver (data: I) -> O { + let mut s = s!(""); + + for i in 0.. { + let st = format!("{data}{i}"); + let hash = md5::compute(st); + + let repr = format!("{:x}", hash); + + if repr.starts_with("00000") { + s.push_str(&repr[5..=5]); + if s.len() == 8 { + break; + } + } + } + + s +} + +fn _gold (data: I) -> O { + let mut s = ['\0'; 8]; + + for i in 0.. { + let st = format!("{data}{i}"); + let hash = md5::compute(st); + + let repr = format!("{:x}", hash); + + if repr.starts_with("00000") { + let idx = (&repr[5..=5]).parse::().unwrap_or(usize::MAX); + let val = (&repr[6..=6]).chars().next().unwrap(); + + if idx < s.len() && s[idx] == '\0' { + s[idx] = val; + } + + if s.iter().all(|&e| e != '\0') { break; } + } + } + + s.into_iter().collect() +} + +#[cfg(test)] +mod test { + use super::*; + + fn read () -> I { + "abbhdwsy" + } + + + #[test] + fn silver () { + let data = read(); + let ans = _silver(data); + + assert_eq!(ans, s!("801b56a7")) + } + + #[test] + fn gold () { + let data = read(); + let ans = _gold(data); + + assert_eq!(ans, s!("424a0197")) + } +}