Day 3: Lobby

Year: 2025

Entire question here.

We are given several line separated strings of numbers (0-9) and a number n, for each string, we have two select two characters, appending which, in order, produces the largest number; and return their sum.

For example, in the string “97856483” and n = 2, our answer is 98. In “811111111111119”, we have 89!

The only differentiating part in part 1 and part 2 is n. Part 1 has n = 2, and part 2 has it equal to 12.

Let’s get started then, and get done with the boilerplate first.

use std::fs;
fn main() {
let input = fs::read_to_string("./sample.txt").unwrap();
let mut sum = 0;
for line in input.lines() {
let num = parse(&line, 12);
sum += num;
}
println!("Final number: {sum}");
}

The real meat is in the parse function!

Let us go through the logic.

  1. We store three variables, sum, lastindex, and placeholder.

    1. sum is the running sum for the current line.
    2. last_index- We only search after lastindex.
    3. placeholder- To store the place value we are currently searching for. For example, 10s, 100s, etc.
    fn parse(line: &str, pl: u32) -> u64 {
    let mut sum: u64 = 0;
    let mut last_index: isize = -1;
    let mut placeholder: i32 = pl as i32 - 1;
    <<logic>>
    }
  2. Now onto the loop!! We go through each character in the line, starting after the lastindex and check if the current char is equal to currnum (currnum starts from 9 and ticks down each time we can’t find that number in the line). One thing to note is the range in which we check the chars, starting from last_index + 1 to length of the line - placeholder!

    while placeholder >= 0 {
    let mut found = false;
    for curr_num in (0u64..=9).rev() {
    for (i, c) in line.chars().enumerate() {
    if i as isize <= last_index {
    continue;
    }
    if let Some(num) = c.to_digit(10) {
    if num as u64 == curr_num
    && i < line.len() - placeholder as usize
    {
    last_index = i as isize;
    sum += curr_num * 10_u64.pow(placeholder as u32);
    placeholder -= 1;
    found = true;
    break;
    }
    }
    }
    if found {
    break;
    }
    }
    if !found {
    break;
    }
    }
    sum

We have our final program

main.rs
use std::fs;
fn main() {
let input = fs::read_to_string("./sample.txt").unwrap();
let mut sum = 0;
for line in input.lines() {
let num = parse(&line, 12);
sum += num;
}
println!("Final number: {sum}");
}
fn parse(line: &str, pl: u32) -> u64 {
let mut sum: u64 = 0;
let mut last_index: isize = -1;
let mut placeholder: i32 = pl as i32 - 1;
while placeholder >= 0 {
let mut found = false;
for curr_num in (0u64..=9).rev() {
for (i, c) in line.chars().enumerate() {
if i as isize <= last_index {
continue;
}
if let Some(num) = c.to_digit(10) {
if num as u64 == curr_num
&& i < line.len() - placeholder as usize
{
last_index = i as isize;
sum += curr_num * 10_u64.pow(placeholder as u32);
placeholder -= 1;
found = true;
break;
}
}
}
if found {
break;
}
}
if !found {
break;
}
}
sum
}