This commit is contained in:
2024-12-06 10:04:09 +01:00
parent 8fd9bcd63a
commit 49633b8504
7 changed files with 105 additions and 1 deletions

View File

@@ -4,3 +4,4 @@ version = "0.1.0"
edition = "2021"
[dependencies]
md5 = { workspace = true }

14
y2016/src/bin/d5.rs Normal file
View File

@@ -0,0 +1,14 @@
use y2016::days::d5;
fn main() {
part1();
part2();
}
fn part1() {
println!("{}", d5::process_part1("ojvtpuvg"));
}
fn part2() {
println!("{}", d5::process_part2("ojvtpuvg"));
}

83
y2016/src/days/d5.rs Normal file
View File

@@ -0,0 +1,83 @@
use std::io::{stdout, Write};
pub fn process_part1(input: &str) -> String {
let mut password = String::new();
let mut n = 0;
let mut col = 1;
print!("________");
loop {
let hash = md5::compute(format!("{input}{n}"));
let hash = format!("{hash:x}");
let mut chars = hash.chars().skip(5);
let char = chars.next().unwrap();
print!("\x1b[{col}G{char}");
if hash.split_at(5).0 == "00000" {
col += 1;
password.push(char);
}
if password.len() == 8 {
println!();
return password;
}
n += 1;
}
}
pub fn process_part2(input: &str) -> String {
let mut password = vec!['_'; 8];
let mut n = 0;
print!("________");
loop {
if !password.contains(&'_') {
println!();
return password.into_iter().collect();
}
let hash = md5::compute(format!("{input}{n}"));
let hash = format!("{hash:x}");
if hash.split_at(5).0 == "00000" {
let mut chars = hash.chars().skip(5);
let position = match chars.next().unwrap().to_digit(10) {
Some(position) => {
if position > 7 {
n += 1;
continue;
}
if password[position as usize] != '_' {
n += 1;
continue;
}
position
}
None => {
n += 1;
continue;
}
};
let char = chars.next().unwrap();
print!("\x1b[{}G{char}", position + 1);
//println!("{}", password.clone().into_iter().collect::<String>());
let _ = stdout().flush();
password[position as usize] = char;
}
n += 1;
}
}
#[cfg(test)]
mod tests {
use super::*;
const INPUT: &str = "abc";
#[test]
fn part1() {
let result = process_part1(INPUT);
assert_eq!(result, "18f47a30".to_string());
}
#[test]
fn part2() {
let result = process_part2(INPUT);
assert_eq!(result, "05ace8e3".to_string());
}
}

View File

@@ -5,3 +5,5 @@ pub mod d2;
pub mod d3;
pub mod d4;
pub mod d5;