JonathanGupton

Advent of Code 2022 - Day 6 #2

Dec 6th, 2022
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.43 KB | None | 0 0
  1. use std::collections::VecDeque;
  2.  
  3. fn find_start_of_next_packet(packet: &str, distinct: usize) -> usize {
  4.     let mut position = 0;
  5.     // count of each letter found in distinct range
  6.     let mut letters: [u32; 26] = [0; 26];
  7.     // queue containing the current window of characters
  8.     let mut queue: VecDeque<char> = VecDeque::with_capacity(distinct);
  9.  
  10.     let mut distinct_count: usize = 0;
  11.  
  12.     let mut packet_iter = packet.chars();
  13.  
  14.     // Load the holding deque and char counts
  15.     for _ in 0..distinct {
  16.         if let Some(c) = packet_iter.next() {
  17.             queue.push_back(c);
  18.             if letters[(c as usize) - 97usize] == 0 {
  19.                 distinct_count += 1;
  20.             }
  21.             letters[(c as usize) - 97usize] += 1;
  22.  
  23.             position += 1;
  24.         }
  25.     }
  26.  
  27.     // loop through chars to find break point
  28.     while let Some(c) = packet_iter.next() {
  29.         if distinct_count == distinct {
  30.             break;
  31.         } else {
  32.             let remove = queue.pop_front().unwrap();
  33.             letters[(remove as usize) - 97usize] -= 1;
  34.             if letters[(remove as usize) - 97usize] == 0 {
  35.                 distinct_count -= 1;
  36.             }
  37.             queue.push_back(c);
  38.             if letters[(c as usize) - 97usize] == 0 {
  39.                 distinct_count += 1;
  40.             }
  41.             letters[(c as usize) - 97usize] += 1;
  42.             position += 1;
  43.         }
  44.     }
  45.  
  46.     position
  47. }
  48.  
Advertisement
Add Comment
Please, Sign In to add comment