Complete day 6

This commit is contained in:
Timothy Warren 2022-12-06 13:54:34 -05:00
parent 70e430db35
commit a17504ddf0

View File

@ -1,37 +1,50 @@
fn find_num_chars_before_marker(chars: &Vec<char>) -> usize { fn find_num_chars_before_marker(chars: &Vec<char>, marker_size: usize) -> usize {
let mut iter = chars.iter().enumerate().peekable(); let mut iter = chars.iter().enumerate();
for (i, _) in &mut iter { 'outer: for (i, _) in &mut iter {
let zero = chars.get(i); // Look marker_size -1 characters forward so we can check for duplicate characters
let one = chars.get(i + 1); let mut cursor: Vec<char> = Vec::new();
let two = chars.get(i + 2); for n in 0..marker_size {
let three = chars.get(i + 3); cursor.push(*chars.get(i + n).unwrap());
}
let mut cursor: Vec<char> = vec![*zero.unwrap(), *one.unwrap(), *two.unwrap(), *three.unwrap()];
cursor.sort_unstable(); cursor.sort_unstable();
// If there's a duplicate character, go forward // If there's a duplicate character, go forward
if cursor[0] == cursor[1] || cursor[1] == cursor[2] || cursor[2] == cursor[3] || i < 4 { for (n, ch) in cursor.iter().enumerate() {
continue; if let Some(other) = cursor.get(n + 1) {
if ch == other {
continue 'outer;
}
}
} }
// Since we are looking 3 characters farther than the current iteration, // Since we are looking farther than the current iteration,
// we need to add that to the returned index, plus an extra one, because // we need to add the marker size that to the returned index
// the array is zero-indexed return i + marker_size;
return i + 4;
} }
panic!("Marker not found"); panic!("Marker not found");
} }
fn find_packet_marker(chars: &Vec<char>) -> usize {
find_num_chars_before_marker(chars, 4)
}
fn find_message_marker(chars: &Vec<char>) -> usize {
find_num_chars_before_marker(chars, 14)
}
fn main() { fn main() {
let file_str = include_str!("input.txt"); let file_str = include_str!("input.txt");
let chars: Vec<char> = file_str.chars().collect(); let chars: Vec<char> = file_str.chars().collect();
let chars_before_marker = find_num_chars_before_marker(&chars);
println!( println!(
"Part 1: Number of characters before start-of-packet marker: {}", "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)
); );
} }