Café & Tapioca

Advent of Code 2024 | Dia 2

Prólogo:

Desafio 1 (dia 2):

— Day 2: Red-Nosed Reports —

Sequence
7 6 4 2 1
1 2 7 8 9
9 7 6 2 1
1 3 2 4 5
8 6 4 4 1
1 3 6 7 9
SequenceStatusReason
7 6 4 2 1SafeThe levels are all decreasing by 1 or 2.
1 2 7 8 9Unsafe2 7 is an increase of 5.
9 7 6 2 1Unsafe6 2 is a decrease of 4.
1 3 2 4 5Unsafe1 3 is increasing but 3 2 is decreasing.
8 6 4 4 1Unsafe4 4 is neither an increase or a decrease.
1 3 6 7 9SafeThe levels are all increasing by 1, 2, or 3.

Evoluções no código:

fn is_safe(report: &Vec<i32>) -> Result<bool, Error> {
    let mut increasing: bool = true;
    let mut decreasing: bool = true;

    for i in 0..report.len() - 1 {
        if report[i] < report[i + 1] {
            decreasing = false;
        }
        if report[i] > report[i + 1] {
            increasing = false; 
        }
    }

    Ok(increasing || decreasing)
}
fn is_safe(report: &Vec<i32>) -> Result<bool, Error> {
    let is_increasing = report.windows(2).all(|num| num[1] > num[0]);
    let is_decreasing = report.windows(2).all(|num| num[0] > num[1]);

    if !is_increasing && !is_decreasing {
        return Ok(false);
    }

    Ok(report.windows(2).all(|num| (num[1] - num[0]).abs() <= 3))
}

Desafio 2 (dia 2):

SequenceStatusReason
7 6 4 2 1SafeSafe without removing any level.
1 2 7 8 9UnsafeUnsafe regardless of which level is removed.
9 7 6 2 1UnsafeUnsafe regardless of which level is removed.
1 3 2 4 5SafeSafe by removing the second level, 3.
8 6 4 4 1SafeSafe by removing the third level, 4.
1 3 6 7 9SafeSafe without removing any level.
fn is_report_safe(report: &Vec<i32>, use_dampener: bool) -> Result<bool, Error> {
    // verificando validade do report 
    // antes de executar a primeira remoção
    if is_safe(report)? {
        return Ok(true);
    }

    if use_dampener {
        for i in 0..report.len() {
            let mut report_copy = report.clone();

            // esse elemento só será removido caso o array
            // não se confirme válido no primeiro if
            report_copy.remove(i);
            if is_safe(&report_copy)? {
                return Ok(true);
            }
        }
    }

    // caso após todas as iterações o array continue inválido
    // ele sai do escopo e retorna falso
    Ok(false)
}

Considerações finais:

#adventofcode #rust