Advent of Code 2019 - Day 4

Advent of CodeRust

Another day done, just 20 more left. Today's challenge was this time easier than yesterday's.

I just wasted a lot of time because I'm bad at math and my get_digits truncated one of the digits at first. Otherwise it was easy todo.

Code

fn get_digits(number: i32) -> Vec<i32> {
    let mut n = number;
    let mut digits: Vec<i32> = Vec::new();
    while n > 0 {
        digits.push(n % 10);
        n /= 10;
    }
    digits.reverse();
    digits
}

fn is_valid_password(digits: &Vec<i32>) -> bool {
    let mut has_double = false;
    for i in 1..digits.len() {
        if digits[i - 1] == digits[i] {
            has_double = true;
        }

        if digits[i - 1] > digits[i] {
            return false;
        }
    }
    has_double
}

fn is_valid_password_2(digits: &Vec<i32>) -> bool {
    let mut doubles: [i8; 10] = [0; 10];
    for i in 1..digits.len() {
        if digits[i - 1] == digits[i] {
            doubles[digits[i] as usize] += 1;
        }

        if digits[i - 1] > digits[i] {
            return false;
        }
    }
    doubles.iter().any(|x| *x == 1)
}

pub fn part_one(input: &str) -> i32 {
    let range: Vec<i32> = input.split('-').map(|x| x.parse().unwrap()).collect();
    (range[0]..=range[1])
        .map(get_digits)
        .filter(|x| is_valid_password(x))
        .count() as i32
}

pub fn part_two(input: &str) -> i32 {
    let range: Vec<i32> = input.split('-').map(|x| x.parse().unwrap()).collect();
    (range[0]..=range[1])
        .map(get_digits)
        .filter(|x| is_valid_password_2(x))
        .count() as i32
}

Benchmarks

2019 - Day 04 - Part 1 time: 42.903636ms
2019 - Day 04 - Part 2 time: 42.221314ms

Feedback or Questions?

I don't have a direct way to leave comments on posts. But if you want to give some feedback or have some questions you can contact in other ways.

©2019–2021 Severin Kaderli