From a17504ddf02e7fe2fbd6740bb23e225d0298aad8 Mon Sep 17 00:00:00 2001 From: Timothy Warren Date: Tue, 6 Dec 2022 13:54:34 -0500 Subject: [PATCH] Complete day 6 --- day6/src/main.rs | 49 ++++++++++++++++++++++++++++++------------------ 1 file changed, 31 insertions(+), 18 deletions(-) diff --git a/day6/src/main.rs b/day6/src/main.rs index a87be42..9daa4c0 100644 --- a/day6/src/main.rs +++ b/day6/src/main.rs @@ -1,37 +1,50 @@ -fn find_num_chars_before_marker(chars: &Vec) -> usize { - let mut iter = chars.iter().enumerate().peekable(); +fn find_num_chars_before_marker(chars: &Vec, marker_size: usize) -> usize { + let mut iter = chars.iter().enumerate(); - for (i, _) in &mut iter { - let zero = chars.get(i); - let one = chars.get(i + 1); - let two = chars.get(i + 2); - let three = chars.get(i + 3); - - let mut cursor: Vec = vec![*zero.unwrap(), *one.unwrap(), *two.unwrap(), *three.unwrap()]; + 'outer: for (i, _) in &mut iter { + // Look marker_size -1 characters forward so we can check for duplicate characters + let mut cursor: Vec = Vec::new(); + for n in 0..marker_size { + cursor.push(*chars.get(i + n).unwrap()); + } cursor.sort_unstable(); // If there's a duplicate character, go forward - if cursor[0] == cursor[1] || cursor[1] == cursor[2] || cursor[2] == cursor[3] || i < 4 { - continue; + for (n, ch) in cursor.iter().enumerate() { + if let Some(other) = cursor.get(n + 1) { + if ch == other { + continue 'outer; + } + } } - // Since we are looking 3 characters farther than the current iteration, - // we need to add that to the returned index, plus an extra one, because - // the array is zero-indexed - return i + 4; + // Since we are looking farther than the current iteration, + // we need to add the marker size that to the returned index + return i + marker_size; } panic!("Marker not found"); } +fn find_packet_marker(chars: &Vec) -> usize { + find_num_chars_before_marker(chars, 4) +} + +fn find_message_marker(chars: &Vec) -> usize { + find_num_chars_before_marker(chars, 14) +} + fn main() { let file_str = include_str!("input.txt"); let chars: Vec = file_str.chars().collect(); - let chars_before_marker = find_num_chars_before_marker(&chars); - println!( "Part 1: Number of characters before start-of-packet marker: {}", - chars_before_marker + find_packet_marker(&chars) + ); + + println!( + "Part 2: Number of characters before start-of-message marker: {}", + find_message_marker(&chars) ); }