feat: add day 5 part 2

This commit is contained in:
Xavier Morel
2024-11-19 15:46:42 +01:00
parent 1fa15639d4
commit 98e6f49561

View File

@@ -1,41 +1,55 @@
advent_of_code::solution!(5); advent_of_code::solution!(5);
use md5; fn get_valid_digests(prefix: &str) -> impl Iterator<Item = String> + '_ {
(1..)
.flat_map(move |x| {
fn get_char(data: &str) -> Option<char> { let data = format!("{}{:?}", prefix, x);
let digest = format!("{:x}", md5::compute(data)); let digest = format!("{:x}", md5::compute(data));
if digest.starts_with("00000") { if digest.starts_with("00000") {
digest.chars().nth(5) Some(digest)
} else { } else {
None None
} }
})
// .filter(|x| x.is_some())
// .map(|x| x.unwrap())
} }
pub fn part_one(input: &str) -> Option<String> { pub fn part_one(input: &str) -> Option<String> {
let input = input let input = input.strip_suffix("\n").unwrap_or(input);
.strip_suffix("\n") let res: String = get_valid_digests(input)
.unwrap_or(input); .take(8)
let mut res: Vec<char> = Vec::new(); .map(|x| x.chars().nth(5).unwrap())
for x in 1.. { .collect();
if let Some(chr) = get_char(format!("{}{}", input, x).as_str()) { Some(res)
println!("Found {:?} at index {:?}", chr, x);
res.push(chr);
if res.len() == 8 {
break;
}
}
if x > 100_000_000 {
break;
}
}
Some(res.into_iter().collect())
} }
pub fn part_two(input: &str) -> Option<String> { pub fn part_two(input: &str) -> Option<String> {
None let input = input.strip_suffix("\n").unwrap_or(input);
let res: [Option<char>; 8] = [None; 8];
let end_res: String = get_valid_digests(input)
.scan(res, |state, digest| {
let char_to_put: char = digest.chars().nth(6).unwrap();
if let Ok(pos_nth) = String::from(digest.chars().nth(5).unwrap()).parse::<usize>() {
if pos_nth < 8 && state[pos_nth].is_none() {
state[pos_nth] = Some(char_to_put);
// for c in &mut *state {
// if let Some(c) = c {
// print!("{}", c);
// } else {
// print!("_");
// }
// }
// println!(" - put {} in {:?} - digest {}", char_to_put, pos_nth, digest);
}
}
Some(*state) // .clone())
})
.filter(|s| s.iter().all(|x| x.is_some()))
.take(1)
.flat_map(|r| r.iter().map(|x| x.unwrap()).collect::<Vec<_>>())
.collect();
Some(end_res)
} }
#[cfg(test)] #[cfg(test)]
@@ -51,6 +65,6 @@ mod tests {
#[test] #[test]
fn test_part_two() { fn test_part_two() {
let result = part_two(&advent_of_code::template::read_file("examples", DAY)); let result = part_two(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, None); assert_eq!(result, Some("05ace8e3".into()));
} }
} }