diff --git a/2022/Cargo.toml b/2022/Cargo.toml index 9d4c100..eaa0ef5 100644 --- a/2022/Cargo.toml +++ b/2022/Cargo.toml @@ -27,6 +27,10 @@ path = "src/day4.rs" name = "day5" path = "src/day5.rs" +[[bin]] +name = "day6" +path = "src/day6.rs" + # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/2022/src/day6.rs b/2022/src/day6.rs new file mode 100644 index 0000000..f06d701 --- /dev/null +++ b/2022/src/day6.rs @@ -0,0 +1,58 @@ +// const DATA: &'static str = "zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw"; +const DATA: &'static str = include_str!("../data/day6.txt"); + + +struct CharCounts { + chars: [u8; 26], +} + +impl CharCounts { + fn new() -> Self { + CharCounts { chars: [0; 26]} + } + + fn idx(c: u8) -> usize { + (c as usize) - (b'a' as usize) + } + + fn inc(&mut self, c: u8) { + self.chars[Self::idx(c)] += 1; + } + + fn dec(&mut self, c: u8) { + self.chars[Self::idx(c)] -= 1; + } + + fn max(&self) -> u8 { + // max only returns None if the iterator is empty + *self.chars.iter().max().unwrap() + } +} + + +fn find_marker(data: &[u8], window_size: usize) -> Option { + let mut window = CharCounts::new(); + for (i, v) in data.iter().enumerate() { + window.inc(*v); + if i > (window_size - 1) { + let dropout = data[i - window_size]; + window.dec(dropout); + } + + if i > (window_size - 1) && window.max() == 1 { + return Some(i + 1); + } + } + None +} + + +fn main() { + let bytes = DATA.trim().as_bytes(); + + let m1 = find_marker(&bytes, 4).unwrap(); + println!("Part 1: {m1}"); + + let m2 = find_marker(&bytes, 14).unwrap(); + println!("Part 2: {m2}"); +} \ No newline at end of file