Advent of Code 2025 - Day 6Trash Compactor

Rust | Problem statement | Source code | Tags: String manipulation

Part 1

If we have a list of operators and a matrix of numbers, then for each operator, its result is just the sum()/product() of the numbers in the corresponding column: numbers.iter().map(|nums| nums[i]).sum().

let operators = operators.split_whitespace().collect::<Vec<&str>>();
let numbers = numbers
.iter()
.map(|s| {
s.split_whitespace()
.map(|s| s.parse::<i64>().unwrap())
.collect::<Vec<i64>>()
})
.collect::<Vec<_>>();
let total = operators
.iter()
.enumerate()
.map(|(i, &op)| match op {
"+" => numbers.iter().map(|nums| nums[i]).sum(),
"*" => numbers.iter().map(|nums| nums[i]).product(),
_ => 0,
})
.sum::<i64>();
rust

Part 2

The intractable part is that each number is scattered across columns; if each one is in a row, the problem would be trivial. So we can simply transpose the input from:

123 328  51 64
45 64 387 23
6 98 215 314
* + * +

To:

1  *
24
356

369+
248
8

32*
581
175

623+
431
4
let mut transposed: Vec<Vec<char>> = vec![Vec::new(); data[0].chars().count()];
for line in data.iter() {
for (i, c) in line.chars().enumerate() {
transposed[i].push(c);
}
}

let transposed = transposed
.into_iter()
.map(|col| col.into_iter().collect::<String>())
.collect::<Vec<String>>()
.join("\n");
rust

Now we can just go chunk by chunk to collect the operators and respective numbers. I start a new chunk whenever I encounter an operator, and push the numbers into the current chunk.

let mut operators = Vec::new();
let mut numbers = Vec::new();
for col in transposed.iter_mut() {
let last = *col.last().unwrap();
if matches!(last, '+' | '*') {
operators.push(last);
col.pop();
numbers.push(Vec::new());
}
let line = col.iter().collect::<String>();
let line = line.trim();
if line.is_empty() {
continue;
}
let val: i64 = col.iter().collect::<String>().trim().parse().unwrap();
numbers.last_mut().unwrap().push(val);
}
rust

The arithmetic is the same as before.