suspiciously straightforward
This commit is contained in:
parent
3b9a3eed0c
commit
166008ebb9
@ -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
|
||||
|
||||
|
58
2022/src/day6.rs
Normal file
58
2022/src/day6.rs
Normal file
@ -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<usize> {
|
||||
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}");
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user