Day 6: Trash Compactor
Megathread guidelines
- Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
- You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL
FAQ
- What is this?: Here is a post with a large amount of details: https://programming.dev/post/6637268
- Where do I participate?: https://adventofcode.com/
- Is there a leaderboard for the community?: We have a programming.dev leaderboard with the info on how to join in this post: https://programming.dev/post/6631465
Uiua
I’m new to Uiua, so probably not the best way to express the solution!
ParseRows ← ( ⊜∘⊸≠@\n ⍜⇌°⊂ # Get the row of operations. ) ParseOperations ← ⊜⊢⊸≠@\s SumCalculations ← ( ≡( ⍣(◇/×°@* | ◇/+°@+ ) ) /+ ) Part₁ ← ( ParseRows ⊓(ParseOperations | ⍉ ≡(⊜⋕⊸≠@\s) # Parse columns. ) SumCalculations ) Part₂ ← ( ParseRows ⊓(ParseOperations | ⊜(□≡(⋕▽⊸≠@\s)) ≡/↥⊸≠@\s⍉ # Parse numbers. ) SumCalculations ) &fras "6.txt" ⊃Part₁ Part₂
( ͡° ͜ʖ├┬┴┬┴
Looks good. I like how you managed to use the same structure for Parts 1 and 2; that’s more than I did. And yours is faster than mine too.
One of us! One of us!
Nice use of the inversion, I always forget that’s a thing
nushell
I was afk when the puzzle went up so I had another go at doing it on my phone in Turmux with my shell’s scripting language. It’s quite nice how your shell is also a REPL so you can build up the answer in pieces, although I wrote a file for the second part.

open input.txt | str replace --all --regex ' +' ' ' | lines | each { $in | str trim } | to text | from csv --noheaders --separator ' ' | reverse | transpose --ignore-titles | each --flatten { |list| transpose | skip 1 | if $list.column0 == '+' { math sum } else { math product } } | math sumPart 2
let input = open input.txt | lines | each { $in | split chars } let last_row = ($input | length) - 1 let last_col = ($input | first | length) - 1 mut op = ' ' mut numbers = [] mut grand_tot = 0 for x in $last_col..0 { if $op == '=' { $op = ' ' continue } let n = 0..($last_row - 1) | each { |y| $input | get $y | get $x } | str join | into int $numbers = ($numbers | append $n) $op = $input | get $last_row | get $x if $op != ' ' { $grand_tot += $numbers | if $op == '+' { math sum } else {math product } $numbers = [] $op = '=' } } $grand_totUiua
This was fun :D
I had a fun experience just throwing the strings with both numbers and spaces at the parse function. In the online pad, everything worked out fine but running the same code on my input locally gave me a “invalid float literal” error.
I thought I’d missed some edge case in the real input again, like is often the case.
Turns out that the Uiua version I used locally had a bug that’s fixed in the latest build. For once it wasn’t directly my fault ^^Code
$ 123 328 51 64 $ 45 64 387 23 $ 6 98 215 314 $ * + * + # &fras "input-6.txt" ◌ Calc ← ( ↘₂⊛⊂"+*"/◇⊂ ≡◇⨬(/+|/×) /+ ) P₁ ← ( ⊜(⊜□⊸≠@ )⊸≠@\n ⊃⊣↘₋₁ ⊙(⍉≡₀◇⋕) Calc ) P₂ ← ( ⊜∘⊸≠@\n ⟜⧻ ⊓⍉(˜↯@ ) ⊜(⊙(□≡⋕)⍜⍉(⊃(⊢⊣)↘₋₁))¬⤚≡⌟≍ Calc ) 1_2 [⊃P₁P₂] ≡(&p &pf $"Part _: ")Haskell
There’s probably a really clever way of abstracting just the difference between the two layouts.
import Data.Char (isSpace) import Data.List (transpose) import Data.List.Split (splitWhen) op '+' = sum op '*' = product part1 = sum . map ((op . head . last) <*> (map read . init)) . (transpose . map words . lines) part2 = sum . map ((op . last . last) <*> map (read . init)) . (splitWhen (all isSpace) . reverse . transpose . lines) main = do input <- readFile "input06" print $ part1 input print $ part2 inputUlua probably has a single character that rotates the input -90 degrees…
Your code really reads like your explaining the solution out loud. That’s so elegant!
Thanks! I try to write code to be readable by humans above all else.
Haskell
import Control.Arrow import Data.Char import Data.List import Text.ParserCombinators.ReadP op "*" = product op "+" = sum part1 s = sum $ zipWith ($) (op <$> a) (transpose $ fmap read <$> as) where (a : as) = reverse . fmap words . lines $ s parseGroups = fst . last . readP_to_S (sepBy (endBy int eol) eol) . filter (/= ' ') where eol = char '\n' int = read <$> munch1 isDigit :: ReadP Int part2 s = sum $ zipWith ($) (op <$> words a) (parseGroups . unlines $ reverse <$> transpose as) where (a : as) = reverse $ lines s main = getContents >>= print . (part1 &&& part2)Managed to keep it compact, but boy, do I hate cephalopod math >_<
Python
from csv import reader from functools import reduce from itertools import pairwise from operator import mul from pathlib import Path from typing import Any, List, Sequence def _calc(values: List[str]) -> int: match values[-1]: case "+": return sum(map(int, values[:-1])) case "*": return reduce(mul, map(int, values[:-1])) case _: return 0 def _transpose(values: Sequence[Sequence[Any]]) -> List[List[Any]]: return [[values[row][col] for row in range(len(values))] for col in range(len(values[0]))] def part_one(input: str) -> int: def _parse_input(input: str) -> List[List[str]]: return _transpose(list(map(lambda r: list(filter(None, r)), reader(input.splitlines(), delimiter=" ")))) return sum(map(_calc, _parse_input(input))) def part_two(input: str) -> int: def _parse_input(input: str) -> List[List[str]]: data = list(input.splitlines()) columns = [t[0] for t in filter(lambda t: t[1] != " ", enumerate(data[-1]))] + [len(data[0])] numbers = [[line[a:b] for line in data[:-1]] for a, b in pairwise(columns)] numbers = [list(filter(None, ["".join(num).strip() for num in column])) for column in map(_transpose, numbers)] return list(map(lambda t: t[0] + [t[1]], zip(numbers, list(filter(None, data[-1].split(" ")))))) return sum(map(_calc, _parse_input(input))) if __name__ == "__main__": input = Path("_2025/_6/input").read_text("utf-8") print(part_one(input)) print(part_two(input))Python
For part1, regex is king. Thought about rotating the grid for part2, but going column by column is simple enough.
view code
import re from operator import add, mul def part1(data: str): # split into row, but do not split into cells yet rows = data.splitlines() m = len(rows) # number of rows # initialize the result and operator arrays # the operators array will store the operator function for each column block # the result array will store the initial value for each column block operators = [] res = [] # using regex to skip variable number of spaces for symbol in re.findall(r'\S', rows[-1]): if symbol == '+': operators.append(add) res.append(0) elif symbol == '*': operators.append(mul) res.append(1) n = len(res) # number of columns # iterate through each row, except the last one for i in range(m-1): # use regex to find all numbers in the row for j, num in enumerate(map(int, re.findall(r'\d+', rows[i]))): # apply the operator to update the result for the appropriate column res[j] = operators[j](res[j], num) return sum(res) def part2(data: str): # completely split into grid grid = [list(line) for line in data.splitlines()] m, n = len(grid), len(grid[0]) res = 0 curr = None # current value of the block op = None # operator for the block for j in range(n): if curr is None: # we just started a new block # update the current value and operator based on the symbol symbol = grid[-1][j] curr = 0 if symbol == '+' else 1 op = add if symbol == '+' else mul # read the number from the column num = 0 for i in range(m-1): if grid[i][j] != ' ': num = num * 10 + int(grid[i][j]) # if there is no number, we are at the end of a block if num == 0: # add the block value to the result # and reset the current value and operator res += curr curr = None op = None continue # otherwise, update the current value using the operator curr = op(curr, num) # finally, don't forget to add the last block value that's being tracked res += curr return res sample = """123 328 51 64 45 64 387 23 6 98 215 314 * + * + """ assert part1(sample) == 4277556 assert part2(sample) == 3263827Go
Damn, I actually reeaally enjoy this one! I didn’t expect the twist of part 2, but somehow it wasn’t that hard to manage.
Here is my modern solution:
day06.go
package main import ( "aoc/utils" "fmt" "regexp" "slices" "strconv" "strings" ) type operation int func (o operation) compute(values []int) int { switch o { case add: sum := 0 for _, val := range values { sum += val } return sum case mul: product := 1 for _, val := range values { product *= val } return product } return 0 } const ( add operation = iota mul ) var allOperationSymbols = []string{"+", "*"} func operationFromSymbol(sym string) operation { switch sym { case "+": return add case "*": return mul default: panic(fmt.Sprintf("wtf is a %s?", sym)) } } type problems struct { values [][]int operations []operation } func (p *problems) feed(column string) { last := string(column[len(column)-1]) done := false if slices.Contains(allOperationSymbols, last) { p.operations = append(p.operations, operationFromSymbol(last)) column = column[:len(column)-1] done = true } val, _ := strconv.Atoi(strings.TrimSpace(column)) idx := len(p.values) - 1 p.values[idx] = append(p.values[idx], val) if done { p.values = append(p.values, []int{}) } } func (p *problems) addLine(line string) (done bool) { parts := strings.Split(line, " ") parts = slices.DeleteFunc(parts, func(elem string) bool { return elem == "" }) if slices.Contains(allOperationSymbols, parts[0]) { p.operations = make([]operation, len(parts)) for idx, sym := range parts { p.operations[idx] = operationFromSymbol(sym) } done = true } else { if len(p.values) == 0 { lenparts := len(parts) p.values = make([][]int, lenparts) for idx := range lenparts { p.values[idx] = []int{} } } for idx, part := range parts { num, _ := strconv.Atoi(part) p.values[idx] = append(p.values[idx], num) } done = false } return done } func (p problems) solve() []int { solutions := make([]int, len(p.values)) for idx, values := range p.values { op := p.operations[idx] solutions[idx] = op.compute(values) } return solutions } func stepOne(input chan string) (int, error) { modernProblems := problems{} for line := range input { done := modernProblems.addLine(line) if done { break } } modernSolutions := modernProblems.solve() sum := 0 for _, solution := range modernSolutions { sum += solution } return sum, nil } func transposeInputChan(input chan string) []string { lines := [][]rune{} for line := range input { lines = append(lines, []rune(line)) } linecount := len(lines) columncount := len(lines[0]) transposed := make([][]rune, columncount) for idx := range transposed { transposed[idx] = make([]rune, linecount) } for row, line := range lines { for col, char := range line { transposed[col][row] = char } } columns := make([]string, len(transposed)) for idx, col := range transposed { columns[idx] = string(col) } return columns } func stepTwo(input chan string) (int, error) { transposedInput := transposeInputChan(input) slices.Reverse(transposedInput) // problem-set with one empty problem. modernProblems := problems{ values: [][]int{[]int{}}, } for _, column := range transposedInput { if matched, _ := regexp.MatchString("^\\s*$", column); matched { continue } modernProblems.feed(column) } // Remove last useless empty problem. modernProblems.values = modernProblems.values[:len(modernProblems.values)-1] modernSolutions := modernProblems.solve() sum := 0 for _, solution := range modernSolutions { sum += solution } return sum, nil } func main() { inputFile := utils.FilePath("day06.txt") utils.RunStep(utils.ONE, inputFile, stepOne) utils.RunStep(utils.TWO, inputFile, stepTwo) }Excel
Pt1 - Its a solution, but the column width on Numbers prevents a full solution
If I get p2 working, I’ll post a new link. Dont think i will have much luck though.
C
Well so much for reading a grid of ints in part 1! For part 2, initially I reworked the parsing to read into a big buffer, but then thought it would be fun to try and use memory-mapped I/O as not to use any more memory than strictly necessary for the final version:
Code
#include <stdio.h> #include <stdlib.h> #include <inttypes.h> #include <ctype.h> #include <assert.h> #include <sys/mman.h> #include <unistd.h> #include <err.h> #define GH 5 int main() { char *data, *g[GH], *p; uint64_t p1=0,p2=0, acc; int len, h=0, i, x,y, val; char op; if ((len = (int)lseek(0, 0, SEEK_END)) == -1) err(1, "<stdin>"); if (!(data = mmap(NULL, len, PROT_READ, MAP_SHARED, 0, 0))) err(1, "<stdin>"); for (i=0; i<len; i++) if (!i || data[i-1]=='\n') { assert(h < GH); g[h++] = data+i; } for (x=0; g[h-1]+x < data+len; x++) { if ((op = g[h-1][x]) != '+' && op != '*') continue; for (acc = op=='*', y=0; y<h-1; y++) { val = atoi(&g[y][x]); acc = op=='+' ? acc+val : acc*val; } p1 += acc; for (acc = op=='*', i=0; ; i++) { for (val=0, y=0; y<h-1; y++) { p = &g[y][x+i]; if (p < g[y+1] && isdigit(*p)) val = val*10 + *p-'0'; } if (!val) break; acc = op=='+' ? acc+val : acc*val; } p2 += acc; } printf("06: %"PRIu64" %"PRIu64"\n", p1, p2); }Ironically for Lisp, a good chunk of the work here is type conversion, because strings, vectors, multidimensional arrays, characters, and numbers don’t have implicit conversions between them; you have to specify what you want explicitly. I also found it easier to manually transpose the character array for part 2 rather than traverse in column-major order, because that makes the relationship between input and output data structure more transparent.
(ql:quickload :str) (ql:quickload :array-operations) (defun parse-line-1 (line) (let ((broken-line (str:split " " (str:collapse-whitespaces (str:trim line))))) (mapcar #'(lambda (s) (cond ((equal s "+") #'+) ((equal s "*") #'*) (t (parse-integer s)))) broken-line))) (defun read-inputs-1 (filename) (let* ((input-lines (uiop:read-file-lines filename))) (mapcar #'parse-line-1 input-lines))) (defun main-1 (filename) (let* ((problems (read-inputs-1 filename)) (arguments (apply #'mapcar #'list (butlast problems)))) (reduce #'+ (mapcar #'apply (car (last problems)) arguments)))) (defun parse-operands-2 (lines) (let* ((initial-rows (length lines)) (initial-cols (length (car lines))) (flat-chars (make-array (list (* initial-rows initial-cols)) :initial-contents (apply #'concatenate 'string lines))) (box-chars (make-array (list initial-rows initial-cols) :displaced-to flat-chars)) (transposed-chars (aops:each-index (i j) (aref box-chars j i)))) (loop for cv across (aops:split transposed-chars 1) for s = (str:trim (coerce cv 'string)) collect (if (zerop (length s)) nil (parse-integer s))))) (defun list-split (xs sep &optional (predicate #'equal)) (let ((current nil) (result nil)) (loop for x in xs do (if (funcall predicate x sep) (progn (setf result (cons (reverse current) result)) (setf current nil)) (setf current (cons x current))) finally (setf result (cons (reverse current) result))) (reverse result))) (defun main-2 (filename) (let* ((lines (uiop:read-file-lines filename)) (operators (parse-line-1 (car (last lines)))) (operands (parse-operands-2 (butlast lines)))) (loop for rator in operators for rands in (list-split operands nil) sum (apply rator rands))))Ruby
I decided to rotate the entire input character-by-character, then parse the numbers (see the full source here)
grid = input.lines.map(&:chomp).map {|l| l.each_char.map.to_a }.to_a transposed = Array.new(grid[0].length) { Array.new(grid.length) } grid.each_with_index do |row, y| row.each_with_index do |col, x| transposed[x][y] = col end end vals = [] ops = [] temp_vals = [] transposed.each do |row| l = row.join("").strip temp_vals << l.scan(/\d+/).map(&:to_i).to_a[0] /[+*]/.match(l) { |m| ops << m.to_s.to_sym } if l == "" vals << temp_vals.compact temp_vals = [] end end vals << temp_vals.compact unless temp_vals.empty? vals.each_with_index.sum do |v, i| v.inject(ops[i]) endKotlin
More grid stuff and two-dimensional problem solving, I like it!
The first part just requires extracting the numbers and operators, transposing the grid and summing/multiplying the numbers.
The second part is also not too hard. I just search for the numbers in the transposed grid, making sure to leave out the last column. That one might contain an operator (“+” or “*”). Remember it for later. If the entire row is made of spaces, we have finished parsing a math problem. Just remember to account for the last one! 😅
As with part one, just reduce the found problems and we’re done!This solution requires the trailing spaces to be present in the input files. I had to disable an option in my IDE to prevent it from breaking my nice solution.
Code
class Day06 : AOCSolution { override val year = 2025 override val day = 6 override fun part1(inputFile: String): String { val worksheet = readResourceLines(inputFile) // Arrange the problem in a grid and transpose it, so that the operation is the last element of each row val problems = worksheet.map { line -> line.trim().split(spaceSplitRegex) }.toGrid().transposed() val grandTotal = problems.rows().sumOf { line -> // Map the all but the last element to a number val numbers = line.mapToLongArray(0, line.lastIndex - 1, String::toLong) // Extract the operation val operation = line.last()[0] // Call the correct reduction // The "else" branch is needed for the compiler when (operation) { ADD -> numbers.sum() MULTIPLY -> numbers.reduce { acc, value -> acc * value } else -> 0 } } return grandTotal.toString() } override fun part2(inputFile: String): String { val worksheet = readResourceLines(inputFile) // In this part the problem is more complicated and dependent on the individual characters. val charGrid = worksheet.map(CharSequence::toList).toCharGrid().transposed() val numbers = mutableListOf<Long>() val sb = StringBuilder(charGrid.width) val problems = buildList { // Begin with an empty operation // Assume the operation will be set to a valid value var operation = SPACE for (y in 0 until charGrid.height) { // Extract each row (transposed column) sb.clear().append(charGrid[y]) // Find the bounds of the number val numberOffset = sb.indexNotOf(SPACE) if (numberOffset != -1) { // A number was found, parse it and add it to the list. val endIndex = sb.indexOfAny(STOP_CHARACTERS, numberOffset + 1) val number = java.lang.Long.parseLong(sb, numberOffset, endIndex, 10) numbers.add(number) // Check whether there is an operation in the last column. // IF so, that's the next relevant operation val lastColumn = sb[sb.lastIndex] if (lastColumn != SPACE) { operation = lastColumn } } else { // No number was found, that's the separator for two calculations. // Finalize the collection and clear the numbers. // `toLongArray` creates a neat copy of the Longs in the list. add(Problem(operation, numbers.toLongArray())) numbers.clear() } } // Add the last remaining problem to the list add(Problem(operation, numbers.toLongArray())) } // Reduce all problems to their solutions and sum them up. val grandTotal = problems.sumOf { problem -> when (problem.operation) { ADD -> problem.numbers.sum() MULTIPLY -> problem.numbers.reduce { acc, value -> acc * value } else -> 0 } } return grandTotal.toString() } private companion object { private const val ADD = '+' private const val MULTIPLY = '*' private const val SPACE = ' ' private val STOP_CHARACTERS = charArrayOf(SPACE, ADD, MULTIPLY) @JvmRecord @Suppress("ArrayInDataClass") private data class Problem(val operation: Char, val numbers: LongArray) }(Browser-based) Javascript
I got lazy and lucky writing the first part; hard-coded the number of lines / operands and it worked on the first try! I didn’t factor in the final block not being padded by spaces on both sides for part 2, and so needed to test on the example code – which has 3 lines of operands instead of the problem input’s 4 lines, so I had to properly solve the problem across all possible amounts of lines of input 😩.
I am very jealous of all y’all who have a transpose function available in your language of choice.
Code
function part1(inputText) { const [firstArgs, secondArgs, thirdArgs, fourthArgs, operators] = inputText.trim().split('\n').map(line => line.trim().split(/\s+/)); let totalSum = 0; for (let i = 0; i < firstArgs.length; i++) { if (operators[i] === '+') { totalSum += Number.parseInt(firstArgs[i], 10) + Number.parseInt(secondArgs[i], 10) + Number.parseInt(thirdArgs[i], 10) + Number.parseInt(fourthArgs[i], 10); } else if (operators[i] === '*') { totalSum += Number.parseInt(firstArgs[i], 10) * Number.parseInt(secondArgs[i], 10) * Number.parseInt(thirdArgs[i], 10) * Number.parseInt(fourthArgs[i], 10); } } return totalSum } { const start = performance.now(); const result = part1(document.body.textContent); const end = performance.now(); console.info({ day: 6, part: 1, time: end - start, result }) } function part2(inputText) { const lines = inputText.trimEnd().split('\n'); const interBlockIndices = []; for (let i = 0; i < lines[0].length; i++) { let allEmpty = true; for (let j = 0; j < lines.length; j++) { if (lines[j][i] !== ' ') { allEmpty = false; break; } } if (allEmpty) { interBlockIndices.push(i); } } interBlockIndices.push(lines[0].length); let totalSum = 0; let blockStart = 0; for (const interBlockIndex of interBlockIndices) { // compute calculation of block [blockStart, interBlockIndex - 1] const operands = []; for (let i = interBlockIndex - 1; i >= blockStart; i--) { // parse operands let operand = 0; for (let j = 0; j < lines.length - 1; j++) { if (lines[j][i] !== ' ') { operand *= 10; operand += Number.parseInt(lines[j][i], 10); } } operands.push(operand) } if (lines.at(-1)[blockStart] === '+') { totalSum += operands.reduce((accu, next) => accu + next, 0); } else if (lines.at(-1)[blockStart] === '*') { totalSum += operands.reduce((accu, next) => accu * next, 1); } // console.debug({ totalSum, operands, blockStart, interBlockIndex }); blockStart = interBlockIndex + 1; } return totalSum; } { const example = `123 328 51 64 45 64 387 23 6 98 215 314 * + * + `; const start = performance.now(); const result = part2(document.body.textContent); // const result = part2(example); const end = performance.now(); console.info({ day: 6, part: 2, time: end - start, result }) }








