Yekong's Blog

A blog about my experiences and thoughts.

Description

Start from the beginning, we need to find out the biggest number with 2 digits by the given input and calculate the sum of all the numbers Rearrange the digits are not allowed

Second question is same as the first question, but we need to find out the biggest number with 12 digits

Code

let mut content = File::open("input")?;
let mut codes = String::new();
content.read_to_string(&mut codes)?;
let batteries = codes.trim().split_whitespace().collect::<Vec<&str>>();

let mut total = 0;

for battery in batteries {
    let mut first = 0;
    let mut number = 0;
    let mut last_biggest_pos = 100;
    let mut pos = 0;
    let len = battery.len();
    
    // loop 12 times as second question requires the biggest number with 12 digits
    for j in (1..=12).rev() {
        for i in pos..len {
            // Convert current character to digit
            let num: i64 = battery.chars().nth(i).unwrap().to_digit(10).unwrap() as i64;
            
            // Check if current number is greater than or equal to the first number
            // and if the remaining length is greater than or equal to the current digit positions
            // we need to ensure that we can get enough digits from the remaining positions
            if max(num, first) == num && len - i >= j {
                if max(num, first) != first {
                    // Only record if the current number is greater than the first number
                    // make sure next loop won't skip the same number
                    // SAMPLE: 81818181223412323
                    // the biggest number should start with 888822.....
                    last_biggest_pos = i + 1;
                }
                first = num;
            }
            // Check if the remaining length is less than the current digit positions
            if len - i < j {
                break;
            }
        }
        if j != 1 {
            let base: i64 = 10;
            number += first * base.pow((j - 1) as u32); // join the number
            first = 0; // Reset first to 0 for the next iteration
        } else {
            number += first;
        }
        pos = last_biggest_pos;
    }
    total += number;
}

println!("Total: {}", total);

// MAX FUNCTION
fn max(a: i64, b: i64) -> i64 {
    if a > b { a } else { b }
}