The archive: 2023, 2024, 2025

Advent of Code.

Each December we work through that year's Advent of Code puzzles in Zhex, one small program per day; three archive years are here so far. Every door links to its puzzle on adventofcode.com, with our own summary of what the puzzle asks — most days cover both parts, and every part appears only after it is solved there.

Day 1Secret Entrance

The password for the North Pole base sits in a safe, and the input lists turns of the safe's dial: each turn is a direction, left or right, plus a number of clicks. The dial shows 0 to 99, starts at 50, and wraps around at both ends. Part one asks how many times the dial points at 0 right after a turn. Part two makes the turns enormous and asks how many times the dial passes over 0 anywhere inside a single turn, not only where it stops.

View on adventofcode.com ↗

Show solution

Output

3
6
day01.zhex
# Advent of Code 2025, day 1 — Secret Entrance (solution words).
# The safe dial runs 0..99 and starts at 50; each input line is one
# rotation, R or L plus a click count. Part 1 counts the rotations that
# end with the dial on 0; part 2 counts every pass over 0, including the
# passes between the start and end of one long rotation.

# / truncates toward zero, and % inherits that, so negative wraps fix up here.
word _floored-mod(value: Int, modulus: Int) -> Int
    let wrapped = value % modulus
    if wrapped < 0
        wrapped + modulus
    else
        wrapped

## Parse newline-separated rotations into signed click counts,
## negative for left turns.
word parse(text: String) -> List<Int>
    let rotations: List<Int> = []
    for line in text.split(text, "\n")
        if text.length(line) > 0
            let clicks = text.to-int(text.slice(line, 1, text.length(line))) try
            if text.slice(line, 0, 1) == "L"
                let added = list.append(rotations, 0 - clicks)
            else
                let added = list.append(rotations, clicks)
    rotations

## Count the rotations that land the dial on 0.
word part-one(rotations: List<Int>) -> Int
    var position = 50
    var zeros = 0
    for rotation in rotations
        position = _floored-mod(position + rotation, 100)
        if position == 0
            zeros = zeros + 1
    zeros

# Zeros passed within one rotation, derived from the unnormalized landing
# spot: a right turn crosses a multiple of 100 once per 100 clicks, a left
# turn the same from the other side, minus a start already sitting on 0.
word _zeros-in-rotation(landed: Int, rotation: Int) -> Int
    if rotation > 0
        landed / 100
    else
        var passed = (100 - landed) / 100
        if landed - rotation == 0
            passed = passed - 1
        passed

## Count every pass over 0, crossings inside one rotation included.
word part-two(rotations: List<Int>) -> Int
    var position = 50
    var zeros = 0
    for rotation in rotations
        let landed = position + rotation
        zeros = zeros + _zeros-in-rotation(landed, rotation)
        position = _floored-mod(landed, 100)
    zeros

# Advent of Code 2025, day 1 — Secret Entrance.
# Reads rotations from stdin until end of input, prints both answers.

word main()
    # shortcut: a rotation line is always R or L plus digits, so this sentinel
    # cannot collide; it stands in for the end-of-file failure because
    # error.detail is not compiled to wasm yet
    let input = buffer.new()
    var done = false
    while not done
        let line = read-line("") catch "~end-of-input~"
        if line == "~end-of-input~"
            done = true
        else
            let added = buffer.add-line(input, line)
    let rotations = parse(buffer.to-text(input)) try
    print(part-one(rotations))
    print(part-two(rotations))

Day 2Gift Shop

The gift shop's price list is riddled with made-up product IDs, and the input is a list of ranges, each written as a first and last ID separated by a dash, all separated by commas. An ID is invalid when its digits are one block repeated exactly twice, like 55 or 123123, with no leading zero. Part one asks for the sum of every invalid ID found inside the ranges. Part two widens the rule: an ID now counts when its digits are one block repeated any number of times, so 555 and 123123123 join the list.

View on adventofcode.com ↗

Show solution

Output

1227775554
4174379265
day02.zhex
# Advent of Code 2025, day 2 — Gift Shop (solution words).
# The input is one line of comma-separated ID ranges, each "first-last".
# An ID is invalid when its digits are one block repeated: exactly twice
# in part 1, any number of times in part 2. Each part sums the invalid IDs.

# Whether the digits are the leading block repeated back to back; the
# caller guarantees the block length divides the digit length.
word _repeats-block(digits: String, block-length: Int) -> Bool
    var same = true
    var index = block-length
    while same and index < text.length(digits)
        if text.slice(digits, index, index + block-length) != text.slice(digits, 0, block-length)
            same = false
        index = index + block-length
    same

## Parse the comma-separated ranges into every ID they expand to.
word parse(text: String) -> List<Int>
    let ids: List<Int> = []
    for part in text.split(text, ",")
        if text.length(part) > 0
            let dash = text.index-of(part, "-")
            let first = text.to-int(text.slice(part, 0, dash)) try
            let last = text.to-int(text.slice(part, dash + 1, text.length(part))) try
            for id in range(first, last + 1)
                list.append(ids, id)
    ids

## Sum the IDs whose digits are one block repeated exactly twice.
word part-one(ids: List<Int>) -> Int
    var total = 0
    for id in ids
        let digits = int.to-string(id)
        if text.length(digits) % 2 == 0 and _repeats-block(digits, text.length(digits) / 2)
            total = total + id
    total

## Sum the IDs whose digits are one block repeated any number of times.
word part-two(ids: List<Int>) -> Int
    var total = 0
    for id in ids
        let digits = int.to-string(id)
        var invalid = false
        var block-length = 1
        while not invalid and block-length <= text.length(digits) / 2
            if text.length(digits) % block-length == 0
                invalid = _repeats-block(digits, block-length)
            block-length = block-length + 1
        if invalid
            total = total + id
    total

# Advent of Code 2025, day 2 — Gift Shop.
# Reads the price list from stdin until end of input, prints both answers.

word main()
    # shortcut: a range is always digits around a dash, so this sentinel cannot
    # collide; it stands in for the end-of-file failure because error.detail is
    # not compiled to wasm yet (#135)
    let input = buffer.new()
    var done = false
    while not done
        let line = read-line("") catch "~end-of-input~"
        if line == "~end-of-input~"
            done = true
        else
            let added = buffer.add-line(input, line)
    let ids = parse(buffer.to-text(input)) try
    print(part-one(ids))
    print(part-two(ids))

Day 3Lobby

The input gives one line of digits per bank of batteries, where each digit is a battery's power rating from 1 to 9. From a bank you switch on exactly two batteries, and their digits, kept in line order, form a two-digit number. Part one asks for the sum of the largest number each bank can produce. Part two switches on twelve batteries per bank instead of two, so each bank's output becomes the largest twelve-digit number its line order allows.

View on adventofcode.com ↗

Show solution

Output

357
3121910778619
day03.zhex
# Advent of Code 2025, day 3 — Lobby (solution words).
# Each input line is one bank of batteries, one digit 1..9 per battery.
# Switching on batteries keeps their line order and forms a number, so the
# best output takes the largest digit that still leaves room for the rest.
# Part 1 forms a two-digit number per bank; part 2 forms twelve digits.

# Largest number keepable in line order: scan a shrinking window for its
# largest digit, take it, and continue after it.
word _best-output(bank: List<Int>, digits: Int) -> Int
    var output = 0
    var start = 0
    var remaining = digits
    while remaining > 0
        var best-digit = 0
        var best-index = start
        for index in range(start, list.length(bank) - remaining + 1)
            let digit = bank[index]
            if digit > best-digit
                best-digit = digit
                best-index = index
        output = output * 10 + best-digit
        start = best-index + 1
        remaining = remaining - 1
    output

## Parse the input into its banks, one digit list per line.
word parse(text: String) -> List<List<Int>>
    let banks: List<List<Int>> = []
    for line in text.split(text, "\n")
        if text.length(line) > 0
            let digits: List<Int> = []
            for index in range(0, text.length(line))
                list.append(digits, text.to-int(text.slice(line, index, index + 1)) try)
            let added = list.append(banks, digits)
    banks

## Sum the largest two-digit number each bank can produce.
word part-one(banks: List<List<Int>>) -> Int
    var total = 0
    for bank in banks
        total = total + _best-output(bank, 2)
    total

## Sum the largest twelve-digit number each bank can produce.
word part-two(banks: List<List<Int>>) -> Int
    var total = 0
    for bank in banks
        total = total + _best-output(bank, 12)
    total

# Advent of Code 2025, day 3 — Lobby.
# Reads the battery banks from stdin until end of input, prints both answers.

word main()
    # shortcut: a bank is always digits 1-9, so this sentinel cannot collide; it
    # stands in for the end-of-file failure because error.detail is not compiled
    # to wasm yet (#135)
    let input = buffer.new()
    var done = false
    while not done
        let line = read-line("") catch "~end-of-input~"
        if line == "~end-of-input~"
            done = true
        else
            let added = buffer.add-line(input, line)
    let banks = parse(buffer.to-text(input)) try
    print(part-one(banks))
    print(part-two(banks))

Day 4Printing Department

The input is a diagram of the printing department floor, with rolls of paper shown as @ marks on a grid. A roll counts as accessible when fewer than four of its eight neighboring positions hold rolls. Part one asks how many rolls on the grid are accessible. Part two keeps removing the accessible rolls round after round — each removal freeing its neighbors — and asks how many rolls come off the floor before the rest are stuck for good.

View on adventofcode.com ↗

Show solution

Output

13
43
day04.zhex
# Advent of Code 2025, day 4 — Printing Department (solution words).
# The input is a floor diagram: @ marks a roll of paper, . an empty spot.
# A roll is accessible while fewer than four of its eight neighbors hold
# rolls. Part 1 counts the accessible rolls; part 2 repeats the removal
# until no roll comes free, counting every roll taken.

## Parse the diagram into its grid rows.
word parse(text: String) -> List<String>
    let grid: List<String> = []
    for line in text.split(text, "\n")
        if text.length(line) > 0
            let added = list.append(grid, line)
    grid

word _occupied(grid: List<String>, x: Int, y: Int) -> Bool
    if y < 0 or y >= list.length(grid)
        false
    else
        let row = grid[y]
        if x < 0 or x >= text.length(row)
            false
        else
            text.slice(row, x, x + 1) == "@"

word _neighbor-count(grid: List<String>, x: Int, y: Int) -> Int
    var count = 0
    for dy in range(-1, 2)
        for dx in range(-1, 2)
            if not (dx == 0 and dy == 0)
                if _occupied(grid, x + dx, y + dy)
                    count = count + 1
    count

## Count the rolls with fewer than four occupied neighbors.
word part-one(grid: List<String>) -> Int
    var accessible = 0
    for y in range(0, list.length(grid))
        let row = grid[y]
        for x in range(0, text.length(row))
            if text.slice(row, x, x + 1) == "@" and _neighbor-count(grid, x, y) < 4
                accessible = accessible + 1
    accessible

# One simultaneous removal round: every accessible roll comes free at once,
# so neighbor counts use the grid as it stood at the round's start.
word _remove-round(grid: List<String>) -> List<String>
    let next: List<String> = []
    for y in range(0, list.length(grid))
        let row = grid[y]
        var rebuilt = ""
        for x in range(0, text.length(row))
            if text.slice(row, x, x + 1) == "@" and _neighbor-count(grid, x, y) < 4
                rebuilt = rebuilt + "."
            else
                rebuilt = rebuilt + text.slice(row, x, x + 1)
        list.append(next, rebuilt)
    next

## Remove accessible rolls round by round to the fixpoint, counting
## every roll removed along the way.
word part-two(grid: List<String>) -> Int
    var current = grid
    var removed = part-one(current)
    var round-removed = removed
    while round-removed > 0
        current = _remove-round(current)
        round-removed = part-one(current)
        removed = removed + round-removed
    removed

# Advent of Code 2025, day 4 — Printing Department.
# Reads the floor diagram from stdin until end of input, prints both answers.

word main()
    # shortcut: a diagram row is always @ and . characters, so this sentinel
    # cannot collide; it stands in for the end-of-file failure because
    # error.detail is not compiled to wasm yet (#135)
    let input = buffer.new()
    var done = false
    while not done
        let line = read-line("") catch "~end-of-input~"
        if line == "~end-of-input~"
            done = true
        else
            let added = buffer.add-line(input, line)
    let grid = parse(buffer.to-text(input))
    print(part-one(grid))
    print(part-two(grid))

Day 5Cafeteria

The input has two sections: a list of fresh-ingredient ID ranges, then a blank line and a list of the ingredient IDs on hand, and the ranges overlap one another. An ID counts as fresh when it falls inside any of the ranges. Part one asks how many of the IDs on hand are fresh. Part two asks how many different IDs the ranges cover between them, with overlapping IDs counted only once.

View on adventofcode.com ↗

Show solution

Output

3
14
day05.zhex
# Advent of Code 2025, day 5 — Cafeteria (solution words).
# The database lists fresh ingredient ID ranges, a blank line, then the
# available ingredient IDs; the ranges are inclusive and may overlap, and
# an ID is fresh when it falls inside any range. Part 1 counts how many of
# the available IDs are fresh; part 2 measures the ranges themselves — the
# total number of distinct IDs they cover, overlaps counted once.

## One inclusive fresh-ID range.
type IdRange = record
    first: Int
    last: Int

## The database: the fresh ranges and the available IDs.
type Database = record
    ranges: List<IdRange>
    ids: List<Int>

## Parse the two sections around the blank line.
word parse(text: String) -> Database
    let ranges: List<IdRange> = []
    let ids: List<Int> = []
    var in-ranges = true
    for line in text.split(text, "\n")
        if in-ranges and text.length(line) == 0
            in-ranges = false
        elif text.length(line) > 0
            if in-ranges
                let dash = text.index-of(line, "-")
                let first = text.to-int(text.slice(line, 0, dash)) try
                let last = text.to-int(text.slice(line, dash + 1, text.length(line))) try
                let added = list.append(ranges, IdRange(first, last))
            else
                let added = list.append(ids, text.to-int(line) try)
    Database(ranges, ids)

word _covers(fresh-range: IdRange, id: Int) -> Bool
    id >= fresh-range.first and id <= fresh-range.last

## Count the available IDs that fall inside any fresh range.
word part-one(database: Database) -> Int
    var fresh = 0
    for id in database.ids
        if list.any(database.ranges, _covers(_, id))
            fresh = fresh + 1
    fresh

word _range-first(fresh-range: IdRange) -> Int
    fresh-range.first

## Measure the union of the fresh ranges: sorted by first ID, a range
## extends the current span while it overlaps and opens a new one after a
## gap, so overlapping IDs count exactly once.
word part-two(database: Database) -> Int
    let sorted = list.sort-by(database.ranges, _range-first(_))
    let opening = sorted[0]
    var total = 0
    var low = opening.first
    var high = opening.last
    for fresh-range in sorted
        if fresh-range.first > high
            total = total + (high - low + 1)
            low = fresh-range.first
            high = fresh-range.last
        elif fresh-range.last > high
            high = fresh-range.last
    total + (high - low + 1)

# Advent of Code 2025, day 5 — Cafeteria.
# Reads the database from stdin until end of input, prints both answers.

word main()
    # The database separates its two sections with a blank line, so the runner
    # branches on the end-of-file detail (error.detail). That word is fenced in
    # the browser build (#135), and the sentinel workaround days 1-4 use cannot
    # detect end-of-file either. The door carries the fence note until the
    # engine lane fixes #135.
    let input = buffer.new()
    var done = false
    while not done
        let line = read-line("") catch problem
            if error.detail(problem, "reason") == "end-of-file"
                done = true
                ""
            else
                error.message(problem)
        if not done
            let added = buffer.add-line(input, line)
    let database = parse(buffer.to-text(input)) try
    print(part-one(database))
    print(part-two(database))

Day 6Trash Compactor

Stuck under a trash compactor, you work through the cephalopods' math homework. The worksheet sets numbers in vertical columns, puts a + or * at the bottom of each problem, and separates problems with a column of spaces; spacing inside a problem can be ignored. Part one asks for the total of all the problems' answers. Part two reveals the numbers must be read the other way: each column of digits, top to bottom, is one number, and an all-space column separates the problems, so the total is taken again over that reading.

View on adventofcode.com ↗

Show solution

Output

4277556
3263827
day06.zhex
# Advent of Code 2025, day 6 — Trash Compactor (solution words).
# The math worksheet stacks each problem's numbers vertically with its
# operator (+ or *) at the bottom; problems sit side by side, separated by
# a full column of spaces. Part 1 reads the numbers row-wise: each row
# lists one number per problem in order. Part 2 reads them column-wise:
# each column of digits, top to bottom, is one number, and an all-space
# column moves to the next problem. Both parts total the problems' answers.

## The worksheet, decoded: its operators plus each problem's numbers read
## row-wise and column-wise.
type Worksheet = record
    operators: List<String>
    rowwise: List<List<Int>>
    columnwise: List<List<Int>>

# The non-space fields of a row, in order.
word _fields(row: String) -> List<String>
    let fields: List<String> = []
    for field in text.split(row, " ")
        if text.length(field) > 0
            let added = list.append(fields, field)
    fields

# One empty number list per problem, ready to fill.
word _empty-columns(count: Int) -> List<List<Int>>
    let columns: List<List<Int>> = []
    for problem in range(0, count)
        let numbers: List<Int> = []
        list.append(columns, numbers)
    columns

## Parse the worksheet: split each data row's numbers problem by problem,
## then stack each column's digits top to bottom into one number per
## column, with all-space columns separating problems.
word parse(text: String) -> Worksheet
    let rows: List<String> = []
    for line in text.split(text, "\n")
        if text.length(line) > 0
            let added = list.append(rows, line)
    let operators = _fields(rows[list.length(rows) - 1])
    let rowwise = _empty-columns(list.length(operators))
    for index in range(0, list.length(rows) - 1)
        let fields = _fields(rows[index])
        for problem in range(0, list.length(operators))
            list.append(rowwise[problem], text.to-int(fields[problem]) try)
    let columnwise = _empty-columns(list.length(operators))
    var problem = 0
    for column in range(0, text.length(rows[0]))
        var digits = ""
        for index in range(0, list.length(rows) - 1)
            let row = rows[index]
            if column < text.length(row)
                let character = text.slice(row, column, column + 1)
                if character != " "
                    digits = digits + character
        if text.length(digits) > 0
            let added = list.append(columnwise[problem], text.to-int(digits) try)
        else
            problem = problem + 1
    Worksheet(operators, rowwise, columnwise)

# Apply one problem's operator to its numbers.
word _apply(operator: String, numbers: List<Int>) -> Int
    var total = 0
    if operator == "*"
        total = 1
    for number in numbers
        if operator == "*"
            total = total * number
        else
            total = total + number
    total

# Total the worksheet under one reading of the numbers.
word _total(operators: List<String>, numbers: List<List<Int>>) -> Int
    var total = 0
    for problem in range(0, list.length(operators))
        total = total + _apply(operators[problem], numbers[problem])
    total

## Total the answers with the numbers read row-wise.
word part-one(worksheet: Worksheet) -> Int
    _total(worksheet.operators, worksheet.rowwise)

## Total the answers with the numbers read column-wise.
word part-two(worksheet: Worksheet) -> Int
    _total(worksheet.operators, worksheet.columnwise)

# Advent of Code 2025, day 6 — Trash Compactor.
# Reads the worksheet from stdin until end of input, prints both answers.

word main()
    # shortcut: a worksheet row is digits, spaces, +, and *, so this sentinel
    # cannot collide; it stands in for the end-of-file failure because
    # error.detail is not compiled to wasm yet (#135)
    let input = buffer.new()
    var done = false
    while not done
        let line = read-line("") catch "~end-of-input~"
        if line == "~end-of-input~"
            done = true
        else
            let added = buffer.add-line(input, line)
    let worksheet = parse(buffer.to-text(input)) try
    print(part-one(worksheet))
    print(part-two(worksheet))

Day 7Laboratories

A broken teleporter reports a fault in its tachyon manifold, and the input draws that manifold: open space, splitter tiles marked ^, and one entry marked S. Beams enter at S and always travel down; a beam that reaches a splitter stops, and two new beams continue from the splitter's left and right sides. Part one asks for the total number of times the beams split. Part two asks how many beam timelines leave the bottom of the diagram, counting every route separately even after beams landing on the same spot merge.

View on adventofcode.com ↗

Show solution

Output

21
40
day07.zhex
# Advent of Code 2025, day 7 — Laboratories (solution words).
# The diagram has open space (.), splitters (^), and one entry (S) where a
# tachyon beam enters moving down. A beam reaching a splitter stops, and
# two beams continue from the splitter's left and right cells; beams that
# land together merge. One row-by-row pass answers both parts: part 1
# counts the splitters a beam reaches, part 2 counts the beam timelines
# that leave the bottom of the diagram.

## Parse the diagram into its rows.
word parse(text: String) -> List<String>
    let grid: List<String> = []
    for line in text.split(text, "\n")
        if text.length(line) > 0
            let added = list.append(grid, line)
    grid

# The row holding the entry marker.
word _entry-row(grid: List<String>) -> Int
    var entry = 0
    var index = 0
    var found = false
    while not found and index < list.length(grid)
        if text.index-of(grid[index], "S") >= 0
            found = true
            entry = index
        index = index + 1
    entry

# The column holding the entry marker.
word _entry-column(grid: List<String>) -> Int
    text.index-of(grid[_entry-row(grid)], "S")

# The starting beams: one timeline at the entry's column.
word _starting-beams(grid: List<String>) -> List<Int>
    let beams: List<Int> = []
    for index in range(0, text.length(grid[0]))
        if index == _entry-column(grid)
            list.append(beams, 1)
        else
            list.append(beams, 0)
    beams

# Beams entering one row leave it as the beams entering the next: on open
# space a beam continues down, on a splitter it splits to the splitter's
# left and right neighbors.
word _advance(row: String, beams: List<Int>) -> List<Int>
    let next: List<Int> = []
    for index in range(0, list.length(beams))
        list.append(next, 0)
    for index in range(0, list.length(beams))
        let count = beams[index]
        if count > 0
            if index < text.length(row) and text.slice(row, index, index + 1) == "^"
                if index > 0
                    next[index - 1] = next[index - 1] + count
                if index < list.length(beams) - 1
                    next[index + 1] = next[index + 1] + count
            else
                next[index] = next[index] + count
    next

## Count the splitters a beam reaches.
word part-one(grid: List<String>) -> Int
    var beams = _starting-beams(grid)
    var splits = 0
    for row-index in range(_entry-row(grid) + 1, list.length(grid))
        let row = grid[row-index]
        for index in range(0, list.length(beams))
            if beams[index] > 0 and index < text.length(row) and text.slice(row, index, index + 1) == "^"
                splits = splits + 1
        beams = _advance(row, beams)
    splits

## Count the beam timelines that leave the bottom of the diagram.
word part-two(grid: List<String>) -> Int
    var beams = _starting-beams(grid)
    for row-index in range(_entry-row(grid) + 1, list.length(grid))
        beams = _advance(grid[row-index], beams)
    var exits = 0
    for count in beams
        exits = exits + count
    exits

# Advent of Code 2025, day 7 — Laboratories.
# Reads the diagram from stdin until end of input, prints both answers.

word main()
    # shortcut: a diagram row is ., ^, and S characters, so this sentinel
    # cannot collide; it stands in for the end-of-file failure because
    # error.detail is not compiled to wasm yet (#135)
    let input = buffer.new()
    var done = false
    while not done
        let line = read-line("") catch "~end-of-input~"
        if line == "~end-of-input~"
            done = true
        else
            let added = buffer.add-line(input, line)
    let grid = parse(buffer.to-text(input))
    print(part-one(grid))
    print(part-two(grid))

Day 8Playground

The input lists the 3D coordinates of junction boxes hung in an underground playground, joined into circuits by strings. Each string joins the closest pair of boxes not yet directly connected; a string between boxes already in one circuit changes nothing. Part one asks for the product of the sizes of the three largest circuits once the 1000 shortest connections have been made. Part two keeps connecting the closest pairs until every box shares one circuit, then asks for the product of the X coordinates of the two boxes whose string completed it.

View on adventofcode.com ↗

Show solution

Output

40
25272
day08.zhex
# Advent of Code 2025, day 8 — Playground (solution words).
# The input lists the 3D positions of junction boxes. Connecting two boxes
# joins their circuits, and connecting boxes already in one circuit does
# nothing. Distances only ever order the candidate pairs, so squared
# straight-line distance ranks them exactly — integer arithmetic
# throughout, no square roots. Part 1 makes a number of the closest
# connections and multiplies the sizes of the three largest circuits;
# part 2 keeps connecting until every box shares one circuit and
# multiplies the completing pair's X coordinates.

## One junction box position.
type Box = record
    x: Int
    y: Int
    z: Int

## One candidate connection between box indexes, ranked by squared
## straight-line distance.
type Connection = record
    distance: Int
    a: Int
    b: Int

## Parse the comma-separated X,Y,Z lines into box records.
word parse(text: String) -> List<Box>
    let boxes: List<Box> = []
    for line in text.split(text, "\n")
        if text.length(line) > 0
            let parts = text.split(line, ",")
            let x = text.to-int(parts[0]) try
            let y = text.to-int(parts[1]) try
            let z = text.to-int(parts[2]) try
            let added = list.append(boxes, Box(x, y, z))
    boxes

word _rank(connection: Connection) -> Int
    connection.distance

# Every candidate connection between two boxes, shortest first.
word _connections(boxes: List<Box>) -> List<Connection>
    let pairs: List<Connection> = []
    for a in range(0, list.length(boxes))
        for b in range(a + 1, list.length(boxes))
            let first = boxes[a]
            let second = boxes[b]
            let dx = first.x - second.x
            let dy = first.y - second.y
            let dz = first.z - second.z
            list.append(pairs, Connection(dx * dx + dy * dy + dz * dz, a, b))
    list.sort-by(pairs, _rank(_))

# The circuit a box belongs to; a box missing from the map is its own.
word _circuit-of(owner: Map<Int, Int>, box: Int) -> Int
    match owner[box]
        case Option.Some(circuit)
            circuit
        case Option.None
            box

# The member list of one circuit; an unknown circuit holds nobody.
word _members-of(members: Map<Int, List<Int>>, circuit: Int) -> List<Int>
    match members[circuit]
        case Option.Some(group)
            group
        case Option.None
            let empty: List<Int> = []
            empty

# Join the circuits of two boxes, merging the smaller into the larger;
# false when they already share one circuit.
word _connect(owner: Map<Int, Int>, members: Map<Int, List<Int>>, a: Int, b: Int) -> Bool
    let circuit-a = _circuit-of(owner, a)
    let circuit-b = _circuit-of(owner, b)
    if circuit-a == circuit-b
        false
    else
        var keep = circuit-a
        var drop = circuit-b
        if list.length(_members-of(members, circuit-b)) > list.length(_members-of(members, circuit-a))
            keep = circuit-b
            drop = circuit-a
        let winners = _members-of(members, keep)
        for box in _members-of(members, drop)
            map.put(owner, box, keep)
            list.append(winners, box)
        map.remove(members, drop)
        true

## Make the closest connections and multiply the sizes of the three
## largest circuits.
word part-one(boxes: List<Box>, connections: Int) -> Int
    let owner: Map<Int, Int> = {}
    let members: Map<Int, List<Int>> = {}
    for index in range(0, list.length(boxes))
        map.put(owner, index, index)
        let alone: List<Int> = []
        list.append(alone, index)
        map.put(members, index, alone)
    let pairs = _connections(boxes)
    var limit = connections
    if limit > list.length(pairs)
        limit = list.length(pairs)
    for index in range(0, limit)
        let pair = pairs[index]
        _connect(owner, members, pair.a, pair.b)
    let sizes: List<Int> = []
    for circuit, group in members
        list.append(sizes, list.length(group))
    let ranked = list.sort(sizes)
    let last = list.length(ranked) - 1
    ranked[last] * ranked[last - 1] * ranked[last - 2]

## Keep connecting the closest pairs until one circuit holds every box,
## then multiply the completing pair's X coordinates.
word part-two(boxes: List<Box>) -> Int
    let owner: Map<Int, Int> = {}
    let members: Map<Int, List<Int>> = {}
    for index in range(0, list.length(boxes))
        map.put(owner, index, index)
        let alone: List<Int> = []
        list.append(alone, index)
        map.put(members, index, alone)
    let pairs = _connections(boxes)
    var circuits = list.length(boxes)
    var index = 0
    var answer = 0
    while circuits > 1 and index < list.length(pairs)
        let pair = pairs[index]
        if _connect(owner, members, pair.a, pair.b)
            circuits = circuits - 1
            if circuits == 1
                let first = boxes[pair.a]
                let second = boxes[pair.b]
                answer = first.x * second.x
        index = index + 1
    answer

# Advent of Code 2025, day 8 — Playground.
# Reads box positions from stdin until end of input, prints both answers.

word main()
    # shortcut: a position line is digits and commas, so this sentinel cannot
    # collide; it stands in for the end-of-file failure because error.detail
    # is not compiled to wasm yet (#135)
    let input = buffer.new()
    var done = false
    while not done
        let line = read-line("") catch "~end-of-input~"
        if line == "~end-of-input~"
            done = true
        else
            let added = buffer.add-line(input, line)
    let boxes = parse(buffer.to-text(input)) try
    # the puzzle fixes 1000 connections for the full list and walks its 20-box
    # example through the ten shortest; the door runs the example
    let connections = if list.length(boxes) > 20
        1000
    else
        10
    print(part-one(boxes, connections))
    print(part-two(boxes))

Day 9Movie Theater

Elves are re-tiling a movie theater floor, and the input lists the coordinates of the red tiles. Any two red tiles can serve as opposite corners of a rectangle of new tiles. Part one asks for the largest area such a rectangle can cover. Part two connects the red tiles in input order into a closed loop of edges and asks for the largest rectangle whose tiles all stay inside that loop.

View on adventofcode.com ↗

Show solution

Output

50
24
day09.zhex
# Advent of Code 2025, day 9 — Movie Theater (solution words).
# The input lists the red tiles, one x,y pair per line, and in input order
# they walk a closed orthogonal loop (consecutive tiles share a row or a
# column; the last connects back to the first). Part 1 takes the largest
# inclusive rectangle over all pairs of red tiles. Part 2 may not lay new
# tiles outside the loop: coordinates compress to the tiles' distinct xs
# and ys, the loop is drawn as a border with a margin ring, the outside is
# flood-filled from the ring's corner by an explicit stack, and a pair's
# rectangle is valid when its compressed footprint holds no outside cell.

type Spot = record
    x: Int
    y: Int

word _abs(value: Int) -> Int
    if value < 0
        0 - value
    else
        value

## Parse newline-separated x,y pairs into the red tiles in input order.
word parse(text: String) -> List<Spot>
    let tiles: List<Spot> = []
    for line in text.split(text, "\n")
        if text.length(line) > 0
            let halves = text.split(line, ",")
            let x = text.to-int(halves[0]) try
            let y = text.to-int(halves[1]) try
            let added = list.append(tiles, Spot(x, y))
    tiles

## Largest inclusive rectangle with two red tiles as opposite corners.
word part-one(tiles: List<Spot>) -> Int
    var best = 0
    for i in range(0, list.length(tiles))
        for j in range(i + 1, list.length(tiles))
            let a = tiles[i]
            let b = tiles[j]
            let area = (_abs(b.x - a.x) + 1) * (_abs(b.y - a.y) + 1)
            if area > best
                best = area
    best

# Sorted duplicates-removed copy: one axis's compressed coordinates.
word _distinct-sorted(values: List<Int>) -> List<Int>
    let out: List<Int> = []
    for value in list.sort(values)
        if list.length(out) == 0 or value != out[list.length(out) - 1]
            let added = list.append(out, value)
    out

# Position of a value in a compressed axis; the caller passes a value the
# axis was built from, so the scan always finds it.
word _compressed(values: List<Int>, value: Int) -> Int
    var index = 0
    var found = -1
    while found < 0
        if values[index] == value
            found = index
        index = index + 1
    found

# Draw the closed loop's border into the compressed grid (+1 margin).
# shortcut: segments are horizontal or vertical by the input contract —
# a diagonal segment (no valid input contains one) draws nothing.
word _draw-border(cells: List<Int>, cols: Int, tiles: List<Spot>, xs: List<Int>, ys: List<Int>)
    let n = list.length(tiles)
    for i in range(0, n)
        var j = i + 1
        if j == n
            j = 0
        let a = tiles[i]
        let b = tiles[j]
        let a-col = _compressed(xs, a.x) + 1
        let b-col = _compressed(xs, b.x) + 1
        let a-row = _compressed(ys, a.y) + 1
        let b-row = _compressed(ys, b.y) + 1
        if a-row == b-row
            var lo-col = a-col
            var hi-col = b-col
            if lo-col > hi-col
                lo-col = b-col
                hi-col = a-col
            for c in range(lo-col, hi-col + 1)
                cells[a-row * cols + c] = 1
        else
            if a-col == b-col
                var lo-row = a-row
                var hi-row = b-row
                if lo-row > hi-row
                    lo-row = b-row
                    hi-row = a-row
                for r in range(lo-row, hi-row + 1)
                    cells[r * cols + a-col] = 1

# Flood-fill the outside from the margin corner. The stack is a plain
# list plus a live-size counter: no list word pops, so a popped slot is
# simply overwritten by the next push at the same depth.
word _flood-outside(cells: List<Int>, rows: Int, cols: Int)
    let stack: List<Int> = []
    var top = 0
    cells[0] = 2
    list.append(stack, 0)
    top = 1
    while top > 0
        top = top - 1
        let at = stack[top]
        let r = at / cols
        let c = at % cols
        if c + 1 < cols and cells[at + 1] == 0
            cells[at + 1] = 2
            if top < list.length(stack)
                stack[top] = at + 1
            else
                let added = list.append(stack, at + 1)
            top = top + 1
        if c > 0 and cells[at - 1] == 0
            cells[at - 1] = 2
            if top < list.length(stack)
                stack[top] = at - 1
            else
                let added = list.append(stack, at - 1)
            top = top + 1
        if r + 1 < rows and cells[at + cols] == 0
            cells[at + cols] = 2
            if top < list.length(stack)
                stack[top] = at + cols
            else
                let added = list.append(stack, at + cols)
            top = top + 1
        if r > 0 and cells[at - cols] == 0
            cells[at - cols] = 2
            if top < list.length(stack)
                stack[top] = at - cols
            else
                let added = list.append(stack, at - cols)
            top = top + 1

# Whether any cell of the inclusive compressed rectangle is outside; the
# two corners may come in either order, so scan low..high per axis.
word _touches-outside(cells: List<Int>, cols: Int, row-a: Int, col-a: Int, row-b: Int, col-b: Int) -> Bool
    var lo-row = row-a
    var hi-row = row-b
    if lo-row > hi-row
        lo-row = row-b
        hi-row = row-a
    var lo-col = col-a
    var hi-col = col-b
    if lo-col > hi-col
        lo-col = col-b
        hi-col = col-a
    var touches = false
    var r = lo-row
    while not touches and r <= hi-row
        var c = lo-col
        while not touches and c <= hi-col
            if cells[r * cols + c] == 2
                touches = true
            c = c + 1
        r = r + 1
    touches

## Largest rectangle whose new tiles all stay inside the loop: compress,
## border, flood the outside, then rescan the pairs — a rectangle of
## original width or height 1 is valid outright because the tiles between
## two red tiles on one line are the loop's own green tiles.
word part-two(tiles: List<Spot>) -> Int
    let xs: List<Int> = []
    let ys: List<Int> = []
    for tile in tiles
        list.append(xs, tile.x)
        list.append(ys, tile.y)
    let distinct-xs = _distinct-sorted(xs)
    let distinct-ys = _distinct-sorted(ys)
    let rows = list.length(distinct-ys) + 2
    let cols = list.length(distinct-xs) + 2
    let cells: List<Int> = []
    for index in range(0, rows * cols)
        list.append(cells, 0)
    _draw-border(cells, cols, tiles, distinct-xs, distinct-ys)
    _flood-outside(cells, rows, cols)
    var best = 0
    for i in range(0, list.length(tiles))
        for j in range(i + 1, list.length(tiles))
            let a = tiles[i]
            let b = tiles[j]
            let area = (_abs(b.x - a.x) + 1) * (_abs(b.y - a.y) + 1)
            if area > best
                if a.x == b.x or a.y == b.y
                    best = area
                else
                    let col-a = _compressed(distinct-xs, a.x) + 1
                    let col-b = _compressed(distinct-xs, b.x) + 1
                    let row-a = _compressed(distinct-ys, a.y) + 1
                    let row-b = _compressed(distinct-ys, b.y) + 1
                    if not _touches-outside(cells, cols, row-a, col-a, row-b, col-b)
                        best = area
    best

# Advent of Code 2025, day 9 — Movie Theater.
# Reads red-tile coordinates from stdin until end of input, prints both answers.

word main()
    # shortcut: a coordinate line is always digits, a comma, digits, so this
    # sentinel cannot collide; it stands in for the end-of-file failure because
    # error.detail is not compiled to wasm yet (#135)
    let input = buffer.new()
    var done = false
    while not done
        let line = read-line("") catch "~end-of-input~"
        if line == "~end-of-input~"
            done = true
        else
            let added = buffer.add-line(input, line)
    let tiles = parse(buffer.to-text(input)) try
    print(part-one(tiles))
    print(part-two(tiles))

Day 10Factory

Each input line describes one broken machine: a light diagram in brackets, button schematics in parentheses naming which lights each press toggles, and joltage requirements in braces. Every machine's lights start off, and each press flips its listed lights on or off. Part one ignores the joltage requirements and asks for the fewest total button presses that set every machine's lights to its target pattern. Part two makes each light's joltage number the exact number of times that light must change state, and asks again for the fewest total button presses.

View on adventofcode.com ↗

Show solution

Output

7
33
day10.zhex
# Advent of Code 2025, day 10 — Factory (solution words).
# Each input line is one machine: a light diagram in brackets (the target
# pattern; machines start dark), button wirings in parentheses naming the
# 0-based lights each press flips, and joltage numbers in braces. Part 1
# finds the fewest presses per machine by breadth-first search over the
# subset of pressed buttons. Part 2 requires every light to be toggled
# exactly its joltage number of times, and minimizes the total presses.

type Machine = record
    target: Int
    lights: Int
    buttons: List<List<Int>>
    joltage: List<Int>

word _pow2(n: Int) -> Int
    var value = 1
    for i in range(0, n)
        value = value * 2
    value

## Parse one machine per line: diagram, buttons, joltage.
word parse(text: String) -> List<Machine>
    let machines: List<Machine> = []
    for line in text.split(text, "\n")
        if text.length(line) > 0
            let tokens = text.split(line, " ")
            let diagram = text.slice(tokens[0], 1, text.length(tokens[0]) - 1)
            var target = 0
            for i in range(0, text.length(diagram))
                if text.slice(diagram, i, i + 1) == "#"
                    target = target + _pow2(i)
            let buttons: List<List<Int>> = []
            for i in range(1, list.length(tokens) - 1)
                let inner = text.slice(tokens[i], 1, text.length(tokens[i]) - 1)
                let lights: List<Int> = []
                for digit in text.split(inner, ",")
                    list.append(lights, text.to-int(digit) try)
                list.append(buttons, lights)
            let joltage: List<Int> = []
            let last = tokens[list.length(tokens) - 1]
            let numbers = text.slice(last, 1, text.length(last) - 1)
            for digit in text.split(numbers, ",")
                list.append(joltage, text.to-int(digit) try)
            let added = list.append(machines, Machine(target, text.length(diagram), buttons, joltage))
    machines

# Flip one light of an encoded state by place value: no bitwise words,
# so the digit comes off with / and % and the place is added or removed.
word _toggle(state: Int, light: Int) -> Int
    let place = _pow2(light)
    if (state / place) % 2 == 0
        state + place
    else
        state - place

# Fewest presses from all-off to the target: breadth-first over encoded
# states, each button pressed at most once (a second press reverts it).
# The queue never pops — a head index walks an append-only list, which
# keeps first-in-first-out order for the shortest press count.
word _fewest-presses(machine: Machine) -> Int
    if machine.target == 0
        0
    else
        let visited: List<Bool> = []
        for i in range(0, _pow2(machine.lights))
            list.append(visited, false)
        let states: List<Int> = []
        let depths: List<Int> = []
        list.append(states, 0)
        list.append(depths, 0)
        visited[0] = true
        var head = 0
        var answer = -1
        while answer < 0 and head < list.length(states)
            let state = states[head]
            let depth = depths[head]
            head = head + 1
            for button in machine.buttons
                var next = state
                for light in button
                    next = _toggle(next, light)
                if next == machine.target
                    answer = depth + 1
                else
                    if not visited[next]
                        visited[next] = true
                        list.append(states, next)
                        let added = list.append(depths, depth + 1)
        answer

## Sum over machines of the fewest presses reaching each target.
word part-one(machines: List<Machine>) -> Int
    var total = 0
    for machine in machines
        total = total + _fewest-presses(machine)
    total

# Fewest presses of the button at `index` that stay possible: one more
# would push its most-used light's joltage negative.
word _max-presses(button: List<Int>, joltage: List<Int>) -> Int
    var bound = joltage[button[0]]
    for light in button
        if joltage[light] < bound
            bound = joltage[light]
    bound

# Minimal total presses assigning counts to buttons from `index` on.
# `joltage` holds the remaining required toggles per light, mutated for
# each trial count and restored on backtrack; an assignment wins only
# when every remainder lands on exactly zero.
word _search(buttons: List<List<Int>>, joltage: List<Int>, index: Int, running: Int, best: Int) -> Int
    if running >= best
        best
    else
        if index == list.length(buttons)
            var zero = true
            for value in joltage
                if value != 0
                    zero = false
            if zero
                running
            else
                best
        else
            let button = buttons[index]
            var result = best
            var count = 0
            while count <= _max-presses(button, joltage) and running + count < result
                for light in button
                    joltage[light] = joltage[light] - count
                let found = _search(buttons, joltage, index + 1, running + count, result)
                if found < result
                    result = found
                for light in button
                    joltage[light] = joltage[light] + count
                count = count + 1
            result

# shortcut: no real input lacks a solution — both references assume one;
# -1 would surface loudly rather than fake a total.
word _fewest-joltage-presses(machine: Machine) -> Int
    let found = _search(machine.buttons, machine.joltage, 0, 0, 1000000000)
    if found == 1000000000
        -1
    else
        found

## Sum over machines of the fewest presses toggling each light exactly
## its joltage number of times.
word part-two(machines: List<Machine>) -> Int
    var total = 0
    for machine in machines
        total = total + _fewest-joltage-presses(machine)
    total

# Advent of Code 2025, day 10 — Factory.
# Reads machine lines from stdin until end of input, prints both answers.

word main()
    # shortcut: a machine line always starts with a bracketed light diagram,
    # so this sentinel cannot collide; it stands in for the end-of-file
    # failure because error.detail is not compiled to wasm yet (#135)
    let input = buffer.new()
    var done = false
    while not done
        let line = read-line("") catch "~end-of-input~"
        if line == "~end-of-input~"
            done = true
        else
            let added = buffer.add-line(input, line)
    let machines = parse(buffer.to-text(input)) try
    print(part-one(machines))
    print(part-two(machines))

Day 11Reactor

The input maps the wiring of a reactor under a factory floor: each line names a device and lists the devices its output feeds, and data never flows backward. Part one asks for the number of distinct routes from the device named you to the device named out. Part two asks for the number of routes from the device named svr to out that pass through both the device named dac and the device named fft.

View on adventofcode.com ↗

Show solution

Output

5
0
day11.zhex
# Advent of Code 2025, day 11 — Reactor (solution words).
# The input is a wiring list: each line names a device and the devices
# its outputs feed, and data never flows backward, so the wiring is a
# DAG. Part 1 counts the distinct routes from "you" to "out". Part 2
# restarts from "svr" and counts only routes that visit both "dac" and
# "fft" — inclusion-exclusion over four plain path counts, each one an
# iterative accumulation over a Kahn topological order (no recursion).

type Wiring = record
    devices: List<String>
    wires: Map<String, List<String>>

## Parse one "device: target target" line per input line.
word parse(text: String) -> Wiring
    let devices: List<String> = []
    let wires: Map<String, List<String>> = {}
    for line in text.split(text, "\n")
        if text.length(line) > 0
            let halves = text.split(line, ": ")
            let name = halves[0]
            let known = map.contains(wires, name)
            map.put(wires, name, text.split(halves[1], " "))
            if not known
                let added = list.append(devices, name)
    Wiring(devices, wires)

# A device's current count in a Map<String, Int>; absent means zero.
word _count-of(counts: Map<String, Int>, name: String) -> Int
    match counts[name]
        case Option.Some(value)
            value
        case Option.None
            0

# A device's wiring list; devices come from the map's own keys, so the
# None arm is unreachable for real inputs.
word _targets-of(wiring: Wiring, device: String) -> List<String>
    match wiring.wires[device]
        case Option.Some(targets)
            targets
        case Option.None
            let none: List<String> = []
            none

# Routes from `start` to "out", treating `skip-one` and `skip-two` as
# deleted devices ("" deletes nothing). Kahn order: count incoming
# wires, queue the sources, then every dequeue pushes its route count
# along its wires; the queue is an append-only list walked by a head
# index, so first-in-first-out needs no pop word.
word _routes(wiring: Wiring, start: String, skip-one: String, skip-two: String) -> Int
    let indegree: Map<String, Int> = {}
    for device in wiring.devices
        if device != skip-one and device != skip-two
            for target in _targets-of(wiring, device)
                if target != skip-one and target != skip-two
                    let counted = map.put(indegree, target, _count-of(indegree, target) + 1)
    let ways: Map<String, Int> = {}
    if start != skip-one and start != skip-two
        let seeded = map.put(ways, start, 1)
    let queue: List<String> = []
    for device in wiring.devices
        if device != skip-one and device != skip-two and _count-of(indegree, device) == 0
            let added = list.append(queue, device)
    var head = 0
    while head < list.length(queue)
        let device = queue[head]
        head = head + 1
        for target in _targets-of(wiring, device)
            if target != skip-one and target != skip-two
                map.put(ways, target, _count-of(ways, target) + _count-of(ways, device))
                map.put(indegree, target, _count-of(indegree, target) - 1)
                if _count-of(indegree, target) == 0
                    let added = list.append(queue, target)
    _count-of(ways, "out")

## Count the distinct routes from "you" to "out".
word part-one(wiring: Wiring) -> Int
    _routes(wiring, "you", "", "")

# Routes from "svr" to "out" through both "dac" and "fft": all routes,
# minus the ones avoiding either, plus the ones avoiding both.
word part-two(wiring: Wiring) -> Int
    let all = _routes(wiring, "svr", "", "")
    let without-dac = _routes(wiring, "svr", "dac", "")
    let without-fft = _routes(wiring, "svr", "fft", "")
    let without-either = _routes(wiring, "svr", "dac", "fft")
    all - without-dac - without-fft + without-either

# Advent of Code 2025, day 11 — Reactor.
# Reads wiring lines from stdin until end of input, prints both answers.

word main()
    # shortcut: a wiring line always contains a colon, so this sentinel
    # cannot collide; it stands in for the end-of-file failure because
    # error.detail is not compiled to wasm yet (#135)
    let input = buffer.new()
    var done = false
    while not done
        let line = read-line("") catch "~end-of-input~"
        if line == "~end-of-input~"
            done = true
        else
            let added = buffer.add-line(input, line)
    let wiring = parse(buffer.to-text(input))
    print(part-one(wiring))
    print(part-two(wiring))

Day 12Christmas Tree Farm

The input lists six present shapes as small grids, then a set of regions, each sized width by length and followed by how many of each shape should fit inside. Presents can be rotated or flipped, must sit on the grid, may not overlap, and cannot stack. Part one asks how many regions can hold all the presents listed for them. Part two is the twelve-day event's finale: with every star collected it asks nothing further, and the customary completion answer is the star itself.

View on adventofcode.com ↗

Show solution

Output

2
*
day12.zhex
# Advent of Code 2025, day 12 — Christmas Tree Farm (solution words).
# The input lists six present shapes as #/. grids, then one line per tree
# region: a width-x-length size and how many of each shape should fit.
# Presents sit on the grid, may rotate and flip, may not overlap or
# stack, and their . holes interlock around other presents. Part 1
# counts the regions that fit everything: cheap filters first (the
# #-cell sum, then a slot count that many presents always satisfy), a
# packing backtracker only when both abstain. Part 2 is the twelve-day
# event's finale — nothing left to compute.

type Form = record
    width: Int
    height: Int
    cells: List<Int>
    pixels: Int

type Region = record
    width: Int
    height: Int
    counts: List<Int>

type Farm = record
    shapes: List<List<Form>>
    regions: List<Region>

# One shape orientation from its grid rows: the # cells as flat offsets
# into the orientation's own width-by-height bounding box.
word _form(rows: List<String>) -> Form
    let width = text.length(rows[0])
    let cells: List<Int> = []
    var pixels = 0
    for r in range(0, list.length(rows))
        for c in range(0, text.length(rows[r]))
            if text.slice(rows[r], c, c + 1) == "#"
                list.append(cells, r * width + c)
                pixels = pixels + 1
    Form(width, list.length(rows), cells, pixels)

# A form's comparable rendering, to drop duplicate orientations.
word _key(form: Form) -> String
    let dims = int.to-string(form.width) + "x" + int.to-string(form.height) + ":"
    dims + text.join(list.map(form.cells, int.to-string(_)), ",")

# Rotate a form a quarter turn right: cell (r, c) lands at (c, h-1-r).
word _rotate-right(form: Form) -> Form
    let cells: List<Int> = []
    for cell in form.cells
        let r = cell / form.width
        let c = cell % form.width
        list.append(cells, c * form.height + form.height - 1 - r)
    Form(form.height, form.width, list.sort(cells), form.pixels)

word _flip-h(form: Form) -> Form
    let cells: List<Int> = []
    for cell in form.cells
        let r = cell / form.width
        let c = cell % form.width
        list.append(cells, r * form.width + form.width - 1 - c)
    Form(form.width, form.height, list.sort(cells), form.pixels)

word _flip-v(form: Form) -> Form
    let cells: List<Int> = []
    for cell in form.cells
        let r = cell / form.width
        let c = cell % form.width
        list.append(cells, (form.height - 1 - r) * form.width + c)
    Form(form.width, form.height, list.sort(cells), form.pixels)

word _add-form(forms: List<Form>, keys: List<String>, form: Form)
    let key = _key(form)
    var seen = false
    for known in keys
        if known == key
            seen = true
    if not seen
        list.append(keys, key)
        let added = list.append(forms, form)

# Every distinct orientation: four rotations, each with its two mirror
# images, duplicates dropped by key.
word _orientations(base: Form) -> List<Form>
    let forms: List<Form> = []
    let keys: List<String> = []
    var current = base
    for turn in range(0, 4)
        _add-form(forms, keys, current)
        _add-form(forms, keys, _flip-h(current))
        _add-form(forms, keys, _flip-v(current))
        current = _rotate-right(current)
    forms

# One "12x5: 1 0 1 0 3 2" region line.
word _region(line: String) -> Region
    let colon = text.index-of(line, ":")
    let size = text.split(text.slice(line, 0, colon), "x")
    let width = text.to-int(size[0]) try
    let height = text.to-int(size[1]) try
    let counts: List<Int> = []
    for count in text.split(text.slice(line, colon + 2, text.length(line)), " ")
        list.append(counts, text.to-int(count) try)
    Region(width, height, counts)

## Parse the shape blocks, the region block last, blank-line separated.
word parse(text: String) -> Farm
    let blocks: List<List<String>> = []
    var block: List<String> = []
    for line in text.split(text, "\n")
        if text.length(line) > 0
            let added = list.append(block, line)
        else
            if list.length(block) > 0
                list.append(blocks, block)
                block = []
    if list.length(block) > 0
        let added = list.append(blocks, block)
    let shapes: List<List<Form>> = []
    for i in range(0, list.length(blocks) - 1)
        let rows: List<String> = []
        for r in range(1, list.length(blocks[i]))
            list.append(rows, blocks[i][r])
        list.append(shapes, _orientations(_form(rows)))
    let regions: List<Region> = []
    for line in blocks[list.length(blocks) - 1]
        list.append(regions, _region(line) try)
    Farm(shapes, regions)

word _pow2(n: Int) -> Int
    var value = 1
    for i in range(0, n)
        value = value * 2
    value

# Fill one anchor column of a region and emit the reachable states. The
# occupancy `occ` holds bits for the cells this column's presents cover
# (bit = column-offset * height + row, no bitwise words, so bits are
# place values tested with / and %); `pend` holds the coverage earlier
# columns already committed into this column's window. Every node emits
# its state shifted past the finished column, then tries one more
# present anchored here. Recursion depth is the presents-per-column
# bound plus one — single digits.
word _fill-column(next: Map<Int, Bool>, occ: Int, pend: Int, code: Int, anchor: Int, width: Int, height: Int, from-shape: Int, shapes: List<List<Form>>, base: Int)
    let shifted = (pend + occ) / _pow2(height)
    let state = shifted * base + code
    if not map.contains(next, state)
        let added = map.put(next, state, true)
    var s = from-shape
    while s < list.length(shapes)
        if (code / _pow2(3 * s)) % 8 > 0
            var f = 0
            while f < list.length(shapes[s])
                let form = shapes[s][f]
                var row = 0
                while row + form.height <= height
                    var bits = 0
                    var ok = true
                    var i = 0
                    while ok and i < list.length(form.cells)
                        let cell = form.cells[i]
                        let bit-col = cell % form.width
                        let bit-row = row + cell / form.width
                        if anchor + bit-col >= width
                            ok = false
                        else
                            let place = _pow2(bit-col * height + bit-row)
                            if ((pend + occ) / place) % 2 == 1
                                ok = false
                            else
                                bits = bits + place
                        i = i + 1
                    if ok
                        _fill-column(next, occ + bits, pend, code - _pow2(3 * s), anchor, width, height, s, shapes, base)
                    row = row + 1
                f = f + 1
        s = s + 1

# Whether the presents pack into the region, by a column sweep: the
# frontier holds every reachable (pending-coverage, remaining-counts)
# state after each anchor column, counts packed three bits per shape.
# shortcut: the state key needs max-shape-width * height + counts bits
# under 63 — 3-wide shapes cap height at 14; taller regions must be
# decided by the filters, which the real input satisfies.
word _region-packs(width: Int, height: Int, shapes: List<List<Form>>, counts: List<Int>) -> Bool
    var code = 0
    for s in range(0, list.length(counts))
        code = code + counts[s] * _pow2(3 * s)
    let base = _pow2(3 * list.length(counts))
    var frontier: Map<Int, Bool> = {}
    let seeded = map.put(frontier, code, true)
    var answer = false
    var anchor = 0
    while not answer and anchor < width and map.length(frontier) > 0
        let next: Map<Int, Bool> = {}
        for key, value in frontier
            if key % base == 0
                answer = true
            else
                _fill-column(next, 0, key / base, key % base, anchor, width, height, 0, shapes, base)
        frontier = next
        anchor = anchor + 1
    if not answer
        for key, value in frontier
            if key % base == 0
                answer = true
    answer

# Whether a region holds its whole present list: the #-cell sum filter,
# then the slot filter (that many max-size presents always fit), then
# the backtracker. The sample's third region passes both filters and
# still fails to pack — the example's whole lesson.
word _region-fits(farm: Farm, region: Region) -> Bool
    let plan: List<Int> = []
    var needed = 0
    var max-width = 0
    var max-height = 0
    for shape in range(0, list.length(region.counts))
        for copy in range(0, region.counts[shape])
            list.append(plan, shape)
            let first = farm.shapes[shape][0]
            needed = needed + first.pixels
            if first.width > max-width
                max-width = first.width
            if first.height > max-height
                max-height = first.height
    if needed > region.width * region.height
        false
    else
        if list.length(plan) == 0
            true
        else
            if list.length(plan) <= (region.width / max-width) * (region.height / max-height)
                true
            else
                let counts: List<Int> = []
                for count in region.counts
                    list.append(counts, count)
                _region-packs(region.width, region.height, farm.shapes, counts)

## Count the regions whose presents all fit.
word part-one(farm: Farm) -> Int
    var total = 0
    for region in farm.regions
        if _region-fits(farm, region)
            total = total + 1
    total

## The event's finale: with every star collected there is nothing left
## to compute — the customary completion answer is the star itself.
word part-two(farm: Farm) -> String
    "*"

# Advent of Code 2025, day 12 — Christmas Tree Farm.
# Reads the shape grids and region lines from stdin until end of input,
# prints both answers.

word main()
    # shortcut: an input line is #/. grid rows or "WxH: counts", so this
    # sentinel cannot collide; it stands in for the end-of-file failure
    # because error.detail is not compiled to wasm yet (#135)
    let input = buffer.new()
    var done = false
    while not done
        let line = read-line("") catch "~end-of-input~"
        if line == "~end-of-input~"
            done = true
        else
            let added = buffer.add-line(input, line)
    let farm = parse(buffer.to-text(input)) try
    print(part-one(farm))
    print(part-two(farm))
Back to top ↑