~anjan/advent2022

5c089cbec69e16c8652baf757e0e81ada2f81911 — Anjandev Momi 2 years ago 74194a1
day 6: part 2 done
1 files changed, 21 insertions(+), 14 deletions(-)

M day6/main.rs
M day6/main.rs => day6/main.rs +21 -14
@@ 4,34 4,41 @@ use std::path::Path;

fn main() {

    assert_eq!(first_marker("mjqjpqmgbljsphdztnvjfqwrcgsmlb"), 7);
    assert_eq!(first_marker("bvwbjplbgvbhsrlpgdmjqwftvncz"), 5);
    assert_eq!(first_marker("nppdvjthqldpwncqszvftbrmjlhg"), 6);
    assert_eq!(first_marker("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg"), 10);
    assert_eq!(first_marker("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw"), 11);
    const BUF_SIZE1:i32 = 4;
    assert_eq!(first_marker("mjqjpqmgbljsphdztnvjfqwrcgsmlb", BUF_SIZE1), 7);
    assert_eq!(first_marker("bvwbjplbgvbhsrlpgdmjqwftvncz", BUF_SIZE1), 5);
    assert_eq!(first_marker("nppdvjthqldpwncqszvftbrmjlhg", BUF_SIZE1), 6);
    assert_eq!(first_marker("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg", BUF_SIZE1), 10);
    assert_eq!(first_marker("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw", BUF_SIZE1), 11);
    const BUF_SIZE2:i32 = 14;
    assert_eq!(first_marker("mjqjpqmgbljsphdztnvjfqwrcgsmlb", BUF_SIZE2), 19);
    assert_eq!(first_marker("bvwbjplbgvbhsrlpgdmjqwftvncz", BUF_SIZE2), 23);
    assert_eq!(first_marker("nppdvjthqldpwncqszvftbrmjlhg", BUF_SIZE2), 23);
    assert_eq!(first_marker("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg", BUF_SIZE2), 29);
    assert_eq!(first_marker("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw", BUF_SIZE2), 26);

    // File hosts must exist in current path before this produces output
    if let Ok(lines) = read_lines("./input") {
        // Consumes the iterator, returns an (Optional) String
        for line in lines {
            if let Ok(ip) = line {
                println!("{}", first_marker(&ip));
                println!("Part 1: {}", first_marker(&ip, BUF_SIZE1));
                println!("Part 2: {}", first_marker(&ip, BUF_SIZE2));
            }
        }
    }
}

fn first_marker(entire_string: &str) -> i32 {
    const BUF_SIZE:i32 = 4;
fn first_marker(entire_string: &str, buf_size: i32) -> i32 {

    'buffer: for buf_start in 0..((entire_string.len() as i32)-BUF_SIZE) {
        let buf_end = buf_start + BUF_SIZE;
    'buffer: for buf_start in 0..((entire_string.len() as i32)-buf_size) {
        let buf_end = buf_start + buf_size;
        // can cast as u8 as long as Im confident input is ASCII
        let buffer: &[u8] = &entire_string.as_bytes()[(buf_start as usize)..(buf_end as usize)];
        for i in 0..(BUF_SIZE-1) {
            for j in (i+1)..BUF_SIZE {
                if buffer[i as usize] != buffer[j as usize] && i == (BUF_SIZE-2){
                    return buf_start+BUF_SIZE;
        for i in 0..(buf_size-1) {
            for j in (i+1)..buf_size {
                if buffer[i as usize] != buffer[j as usize] && i == (buf_size-2){
                    return buf_start+buf_size;
                }
                if buffer[i as usize] == buffer[j as usize] {
                    continue 'buffer;