From 2cb9c207c1233c53121fa36e819bed0a7a0e7972 Mon Sep 17 00:00:00 2001 From: Greg Burri Date: Tue, 6 Dec 2022 13:29:37 +0100 Subject: [PATCH] Day 6 --- src/day06.rs | 43 +++++++++++++++++++++++++++++++++++++++++++ src/main.rs | 7 +++++++ 2 files changed, 50 insertions(+) create mode 100644 src/day06.rs diff --git a/src/day06.rs b/src/day06.rs new file mode 100644 index 0000000..5f0556a --- /dev/null +++ b/src/day06.rs @@ -0,0 +1,43 @@ +pub fn first_marker_pos(signal: &str, n: usize) -> usize { + for (i, c) in signal.chars().collect::>().windows(n).enumerate() { + if !contains_same_char(c) { + return i + n; + } + } + 0 +} + +// Warning: O(n^2). +fn contains_same_char(chars: &[char]) -> bool { + for i in 0..chars.len() { + for j in i+1..chars.len() { + if chars[i] == chars[j] { + return true; + } + } + } + false +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn part1() { + assert_eq!(first_marker_pos("mjqjpqmgbljsphdztnvjfqwrcgsmlb", 4), 7); + assert_eq!(first_marker_pos("bvwbjplbgvbhsrlpgdmjqwftvncz", 4), 5); + assert_eq!(first_marker_pos("nppdvjthqldpwncqszvftbrmjlhg", 4), 6); + assert_eq!(first_marker_pos("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg", 4), 10); + assert_eq!(first_marker_pos("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw", 4), 11); + } + + #[test] + fn part2() { + assert_eq!(first_marker_pos("mjqjpqmgbljsphdztnvjfqwrcgsmlb", 14), 19); + assert_eq!(first_marker_pos("bvwbjplbgvbhsrlpgdmjqwftvncz", 14), 23); + assert_eq!(first_marker_pos("nppdvjthqldpwncqszvftbrmjlhg", 14), 23); + assert_eq!(first_marker_pos("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg", 14), 29); + assert_eq!(first_marker_pos("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw", 14), 26); + } +} \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index 8fbe072..056e7f5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,6 +6,7 @@ mod day02; mod day03; mod day04; mod day05; +mod day06; fn day01() -> String { let f = fs::File::open("data/day01.input").unwrap(); @@ -39,6 +40,11 @@ fn day05() -> String { format!("part1: {}, part2: {}", day05::get_top_as_string(&stacks), day05::get_top_as_string(&stacks2)) } +fn day06() -> String { + let signals = fs::read_to_string("data/day06.input").unwrap(); + format!("part1: {}, part2: {}", day06::first_marker_pos(&signals, 4), day06::first_marker_pos(&signals, 14)) +} + fn format_micros(t: u128) -> String { if t < 10_000 { format!("{} μs", t) @@ -63,6 +69,7 @@ fn main() { day03, day04, day05, + day06, ); let args: Vec = env::args().skip(1).collect(); -- 2.45.2