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 1Trebuchet?!
The input is a calibration document whose lines each hide digits among other characters. A line's value is the two-digit number formed from its first digit and its last digit. Part one asks for the sum of the values over all lines. Part two also counts digits spelled out as one through nine, where a word's last letter may start the next one, and asks for the sum again.
Show solution
Output
142 142
# Advent of Code 2023, day 1 — Trebuchet?! (solution words).
# The calibration document hides one value per line: the two-digit number
# from its first and last digit. Part 1 reads only digit characters; part 2
# also reads digits spelled out as one..nine, and a word's last letter may
# start the next one (eightwo reads as 8 then 2), so the scan checks every
# position instead of replacing words in order.
# The digit a one-character string holds, -1 when it holds none.
word _digit(ch: String) -> Int
text.to-int(ch) catch -1
# The spelled-out digit starting at the line's end slice, -1 for none.
word _word-digit(rest: String) -> Int
if text.starts-with(rest, "one")
1
elif text.starts-with(rest, "two")
2
elif text.starts-with(rest, "three")
3
elif text.starts-with(rest, "four")
4
elif text.starts-with(rest, "five")
5
elif text.starts-with(rest, "six")
6
elif text.starts-with(rest, "seven")
7
elif text.starts-with(rest, "eight")
8
elif text.starts-with(rest, "nine")
9
else
-1
# The line's value from its first and last digit, spelled-out words
# counting only when asked.
word _line-value(line: String, spelled: Bool) -> Int
var first = -1
var last = -1
for index in range(0, text.length(line))
var value = _digit(text.slice(line, index, index + 1))
if spelled and value < 0
value = _word-digit(text.slice(line, index, text.length(line)))
if value >= 0
if first < 0
first = value
last = value
first * 10 + last
## Parse the calibration document into its nonempty lines.
word parse(text: String) -> List<String>
let lines: List<String> = []
for line in text.split(text, "\n")
if text.length(line) > 0
let added = list.append(lines, line)
lines
## Sum the values reading digit characters only.
word part-one(lines: List<String>) -> Int
var total = 0
for line in lines
total = total + _line-value(line, false)
total
## Sum the values with spelled-out digits counted too.
word part-two(lines: List<String>) -> Int
var total = 0
for line in lines
total = total + _line-value(line, true)
total
# Advent of Code 2023, day 1 — Trebuchet?!.
# Reads the calibration document from stdin until end of input, prints both
# answers.
word main()
# shortcut: a calibration line holds letters and digits only, 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 lines = parse(buffer.to-text(input))
print(part-one(lines))
print(part-two(lines))
Day 2Cube Conundrum
The input lists games, each with an ID and a few sets of revealed cubes, every set naming how many red, green, and blue cubes came out of the bag. A game is possible when no set shows more than 12 red, 13 green, or 14 blue cubes at once. Part one asks for the sum of the IDs of the possible games. Part two asks, for each game, for the fewest cubes per color that could have been in the bag — the largest count the game revealed — and sums each game's red, green, and blue fewest multiplied together.
Show solution
Output
8 2286
# Advent of Code 2023, day 2 — Cube Conundrum (solution words).
# Each game line reveals handfuls of cubes; parse keeps, per game, the
# largest count seen per color. Part 1 sums the IDs of games whose per-color
# maxima fit the bag (12 red, 13 green, 14 blue); part 2 takes each game's
# maxima as the fewest cubes per color that could have been in the bag and
# sums their products.
## One game: its ID and the largest count seen per color.
type Game = record
id: Int
red: Int
green: Int
blue: Int
word _parse-game(line: String) -> Game
let colon = text.index-of(line, ":")
let id = text.to-int(text.slice(line, 5, colon)) try
var red = 0
var green = 0
var blue = 0
for reveal in text.split(text.slice(line, colon + 1, text.length(line)), ";")
let clean = text.trim(reveal)
if text.length(clean) > 0
for count-color in text.split(clean, ",")
let parts = text.split(text.trim(count-color), " ")
let count = text.to-int(text.trim(parts[0])) try
let color = text.trim(parts[1])
if color == "red" and count > red
red = count
elif color == "green" and count > green
green = count
elif color == "blue" and count > blue
blue = count
Game(id, red, green, blue)
## Parse the game lines into their per-color maxima.
word parse(text: String) -> List<Game>
let games: List<Game> = []
for line in text.split(text, "\n")
if text.length(line) > 0
let added = list.append(games, _parse-game(line) try)
games
## Sum the IDs of the games the bag could have produced.
word part-one(games: List<Game>) -> Int
var total = 0
for game in games
if game.red <= 12 and game.green <= 13 and game.blue <= 14
total = total + game.id
total
## Sum the products of each game's fewest cubes per color.
word part-two(games: List<Game>) -> Int
var total = 0
for game in games
total = total + game.red * game.green * game.blue
total
# Advent of Code 2023, day 2 — Cube Conundrum.
# Reads the game list from stdin until end of input, prints both answers.
word main()
# shortcut: a game line holds letters, digits, and separators only, 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 games = parse(buffer.to-text(input)) try
print(part-one(games))
print(part-two(games))
Day 3Gear Ratios
The input is a grid of the engine schematic: numbers, periods, and single symbol characters. Any number adjacent to a symbol, even diagonally at a corner, counts as a part number. Part one asks for the sum of all part numbers. Part two calls an asterisk with exactly two adjacent part numbers a gear and asks for the sum of every gear's ratio, the two numbers multiplied together.
Show solution
Output
4361 467835
# Advent of Code 2023, day 3 — Gear Ratios (solution words).
# The schematic is rows of characters; parse collects every maximal run of
# digits as one Part (its row, its first and last column, its value).
# Part 1 sums the parts with a symbol anywhere in their bordering window;
# part 2 sums the products of number pairs around each asterisk that has
# exactly two neighbors. Neighbor scans only — no recursion.
# The digit a one-character string holds, -1 when it holds none.
word _digit(ch: String) -> Int
text.to-int(ch) catch -1
## One found number: its row, its first and last column, its value.
type Part = record
row: Int
first: Int
last: Int
value: Int
## The schematic: its rows and every number found in them.
type Schematic = record
rows: List<String>
parts: List<Part>
word _parse-row(row: String, row-index: Int) -> List<Part>
let parts: List<Part> = []
var index = 0
while index < text.length(row)
if _digit(text.slice(row, index, index + 1)) >= 0
var last = index
var value = 0
while last < text.length(row) and _digit(text.slice(row, last, last + 1)) >= 0
value = value * 10 + _digit(text.slice(row, last, last + 1))
last = last + 1
list.append(parts, Part(row-index, index, last - 1, value))
index = last
else
index = index + 1
parts
## Parse the schematic rows and collect every number in them.
word parse(text: String) -> Schematic
let rows: List<String> = []
let parts: List<Part> = []
for row in text.split(text, "\n")
if text.length(row) > 0
let added = list.append(rows, row)
for row-index in range(0, list.length(rows))
for part in _parse-row(rows[row-index], row-index)
list.append(parts, part)
Schematic(rows, parts)
# Whether the cell holds a symbol: any character that is neither a digit
# nor a period. Out-of-bounds cells never do.
word _symbol-at(rows: List<String>, row: Int, column: Int) -> Bool
if row < 0 or row >= list.length(rows)
false
else
let line = rows[row]
if column < 0 or column >= text.length(line)
false
else
let ch = text.slice(line, column, column + 1)
ch != "." and _digit(ch) < 0
## Sum the numbers with a symbol in their bordering window.
word part-one(schematic: Schematic) -> Int
var total = 0
for part in schematic.parts
var adjacent = false
for row in range(part.row - 1, part.row + 2)
for column in range(part.first - 1, part.last + 2)
if _symbol-at(schematic.rows, row, column)
adjacent = true
if adjacent
total = total + part.value
total
# Whether the part touches the cell: rows within one of it, columns
# overlapping its three-wide window.
word _touches(part: Part, row: Int, column: Int) -> Bool
part.row >= row - 1 and part.row <= row + 1 and part.last >= column - 1 and part.first <= column + 1
## Sum the gear ratios: the products of the two numbers around each
## asterisk with exactly two neighbors.
word part-two(schematic: Schematic) -> Int
var total = 0
for row-index in range(0, list.length(schematic.rows))
let line = schematic.rows[row-index]
for column in range(0, text.length(line))
if text.slice(line, column, column + 1) == "*"
let neighbors: List<Int> = []
for part in schematic.parts
if _touches(part, row-index, column)
let added = list.append(neighbors, part.value)
if list.length(neighbors) == 2
total = total + neighbors[0] * neighbors[1]
total
# Advent of Code 2023, day 3 — Gear Ratios.
# Reads the engine schematic from stdin until end of input, prints both
# answers.
word main()
# shortcut: a schematic row holds digits, periods, and symbols, 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 schematic = parse(buffer.to-text(input))
print(part-one(schematic))
print(part-two(schematic))
Day 4Scratchcards
Each input line is a scratchcard holding two lists of numbers separated by a bar: winning numbers, then the numbers on the card. A card scores one point for its first winning match, and each match after the first doubles its value. Part one asks for the total points across the pile. Part two stops scoring points and starts winning copies instead: each card wins one copy of each of the next cards, as many as it has matches, copies win the same way, and the answer is how many scratchcards end up in the pile, originals included.
Show solution
Output
13 30
# Advent of Code 2023, day 4 — Scratchcards (solution words).
# Each card line holds winning numbers and the card's own numbers around a
# bar. parse reduces a card to its match count — how many of the card's
# numbers are winning. Part 1 scores 2^(matches-1) per card with at least
# one match; part 2 cascades copies: a card's matches each win one copy of
# the following cards, copies win the same way, and the answer is the total
# pile. The cascade runs forward with a per-card count list, an iterative
# List-as-queue — no recursion, so the 256-deep call limit never bites.
# The numbers a space-separated section holds.
word _numbers(section: String) -> List<Int>
let numbers: List<Int> = []
for token in text.split(section, " ")
if text.length(token) > 0
let added = list.append(numbers, text.to-int(token) try)
numbers
word _is(a: Int, b: Int) -> Bool
a == b
# How many of the card's numbers are winning numbers.
word _matches(line: String) -> Int
let halves = text.split(text.split(line, ":")[1], " | ")
let winning = _numbers(halves[0]) try
var matches = 0
let have = _numbers(halves[1]) try
for number in have
if list.any(winning, _is(_, number))
matches = matches + 1
matches
## Parse the pile into each card's match count, in card order.
word parse(text: String) -> List<Int>
let matches: List<Int> = []
for line in text.split(text, "\n")
if text.length(line) > 0
let added = list.append(matches, _matches(line) try)
matches
# Two to the power, by repeated doubling; the exponent is at least one.
word _double(exponent: Int) -> Int
var value = 1
for _ in range(0, exponent - 1)
value = value * 2
value
## Sum the cards' points: one for the first match, doubling per further
## match.
word part-one(matches: List<Int>) -> Int
var total = 0
for card-matches in matches
if card-matches > 0
total = total + _double(card-matches)
total
## Count the whole pile after the copy cascade settles.
word part-two(matches: List<Int>) -> Int
let counts: List<Int> = []
for _ in matches
list.append(counts, 1)
for index in range(0, list.length(matches))
for won in range(index + 1, index + matches[index] + 1)
if won < list.length(counts)
counts[won] = counts[won] + counts[index]
var total = 0
for count in counts
total = total + count
total
# Advent of Code 2023, day 4 — Scratchcards.
# Reads the card pile from stdin until end of input, prints both answers.
word main()
# shortcut: a card line holds "Card N", numbers, and the bar, 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 matches = parse(buffer.to-text(input)) try
print(part-one(matches))
print(part-two(matches))
Day 5If You Give A Seed A Fertilizer
The input lists seed numbers and a chain of maps — seed to soil, soil to fertilizer, and so on up to location — where each line converts a span of source numbers to a same-sized span of destination numbers, and unmapped numbers pass through unchanged. Part one asks for the lowest location number any seed reaches when carried through the whole chain. Part two rereads the seed line as pairs of a starting seed and a count, so the seeds describe huge ranges, and asks the same lowest location over every seed in every range.
Show solution
Output
35 46
# Advent of Code 2023, day 5 — If You Give A Seed A Fertilizer (solution
# words). The almanac lists seeds and a chain of maps, each line converting
# one span of source numbers onto a same-sized span of destination numbers
# with unmapped numbers passing through. Part 1 walks each seed through the
# chain and takes the lowest location. Part 2 reads the seed line as
# first/length pairs — billions of seeds — so the walk is symbolic: spans
# are split at every map boundary they cross and each piece shifts by the
# one range that contains it, never per-seed.
## One map line: destination start, source start, length.
type RangeMap = record
destination: Int
source: Int
length: Int
## The almanac: seed numbers and the map levels, in chain order.
type Almanac = record
seeds: List<Int>
levels: List<List<RangeMap>>
# The numbers a space-separated line holds.
word _numbers(line: String) -> List<Int>
let numbers: List<Int> = []
for token in text.split(line, " ")
if text.length(token) > 0
let added = list.append(numbers, text.to-int(token) try)
numbers
## Parse the seed line and every map block into the chain.
word parse(text: String) -> Almanac
let seeds: List<Int> = []
let levels: List<List<RangeMap>> = []
var current: List<RangeMap> = []
for line in text.split(text, "\n")
if text.length(line) > 0
if text.starts-with(line, "seeds:")
for number in _numbers(text.slice(line, 7, text.length(line))) try
list.append(seeds, number)
elif text.ends-with(line, "map:")
if list.length(current) > 0
let added = list.append(levels, current)
let fresh: List<RangeMap> = []
current = fresh
else
let numbers = _numbers(line) try
let added = list.append(current, RangeMap(numbers[0], numbers[1], numbers[2]))
if list.length(current) > 0
let added = list.append(levels, current)
Almanac(seeds, levels)
# Where one number lands in one map level; unmapped numbers stay.
word _map-one(value: Int, ranges: List<RangeMap>) -> Int
var result = value
var handled = false
for range-map in ranges
if not handled and value >= range-map.source and value < range-map.source + range-map.length
result = value - range-map.source + range-map.destination
handled = true
result
word _location(seed: Int, levels: List<List<RangeMap>>) -> Int
var value = seed
for ranges in levels
value = _map-one(value, ranges)
value
## The lowest location the listed seed numbers reach.
word part-one(almanac: Almanac) -> Int
var lowest = _location(almanac.seeds[0], almanac.levels)
for seed in almanac.seeds
let location = _location(seed, almanac.levels)
if location < lowest
lowest = location
lowest
## One inclusive span of seed numbers.
type Span = record
first: Int
last: Int
word _max(a: Int, b: Int) -> Int
if a > b
a
else
b
word _min(a: Int, b: Int) -> Int
if a < b
a
else
b
# Carry whole spans through one map level. Each span is cut against the
# first range it meets: the outside pieces go back on the pending list for
# the remaining ranges, the overlapping middle shifts by that range, and a
# span no range touches passes through unchanged. The index loop walks a
# list it appends to, so the pieces are re-examined, never lost.
word _map-spans(spans: List<Span>, ranges: List<RangeMap>) -> List<Span>
let mapped: List<Span> = []
let pending: List<Span> = []
for span in spans
list.append(pending, span)
var index = 0
while index < list.length(pending)
let span = pending[index]
var handled = false
for range-map in ranges
if not handled
let source-last = range-map.source + range-map.length - 1
if range-map.source <= span.last and span.first <= source-last
if span.first < range-map.source
let added = list.append(pending, Span(span.first, range-map.source - 1))
if source-last < span.last
let added = list.append(pending, Span(source-last + 1, span.last))
let lo = _max(span.first, range-map.source)
let hi = _min(span.last, source-last)
list.append(mapped, Span(lo - range-map.source + range-map.destination, hi - range-map.source + range-map.destination))
handled = true
if not handled
let added = list.append(mapped, span)
index = index + 1
mapped
## The lowest location any seed in the seed ranges reaches, spans carried
## symbolically through every level.
word part-two(almanac: Almanac) -> Int
let spans: List<Span> = []
var index = 0
while index + 1 < list.length(almanac.seeds)
list.append(spans, Span(almanac.seeds[index], almanac.seeds[index] + almanac.seeds[index + 1] - 1))
index = index + 2
var current = spans
for ranges in almanac.levels
current = _map-spans(current, ranges)
let opening = current[0]
var lowest = opening.first
for span in current
if span.first < lowest
lowest = span.first
lowest
# Advent of Code 2023, day 5 — If You Give A Seed A Fertilizer.
# Reads the almanac from stdin until end of input, prints both answers.
word main()
# The almanac separates its blocks with blank lines, 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 almanac = parse(buffer.to-text(input)) try
print(part-one(almanac))
print(part-two(almanac))
Day 6Wait For It
The input pairs each race's time limit with its record distance. Holding the button down for some whole number of milliseconds sets the boat's speed to that many millimeters per millisecond for the rest of the race, so the distance covered is the hold time times the time left. Part one asks how many hold times beat the record in each race, and multiplies those counts together. Part two rereads the two lines with the spaces ignored, as one huge race, and asks for its winning hold count.
Show solution
Output
288 71503
# Advent of Code 2023, day 6 — Wait For It (solution words). The sheet
# lists each race's time limit and record distance. Holding the button t
# milliseconds leaves T - t milliseconds to travel at t millimeters per
# millisecond, so the distance is t * (T - t); a hold wins when that beats
# the record. Part 2 rereads the two lines as one huge race with the spaces
# ignored, so the same count runs over one long range.
## The sheet: each race's time and record, plus the huge race part 2 reads
## by ignoring the spaces.
type Sheet = record
times: List<Int>
distances: List<Int>
big-time: Int
big-record: Int
# The number tokens a line after its colon holds.
word _tokens(line: String) -> List<String>
let tokens: List<String> = []
for token in text.split(text.slice(line, text.index-of(line, ":") + 1, text.length(line)), " ")
if text.length(token) > 0
let added = list.append(tokens, token)
tokens
# One line's race values.
word _numbers(line: String) -> List<Int>
let numbers: List<Int> = []
for token in _tokens(line)
list.append(numbers, text.to-int(token) try)
numbers
## Parse the Time and Distance lines into paired race values and the
## single huge race.
word parse(text: String) -> Sheet
let times: List<Int> = []
let distances: List<Int> = []
var big-time = 0
var big-record = 0
for line in text.split(text, "\n")
if text.length(line) > 0
if text.starts-with(line, "Time:")
let parsed = _numbers(line) try
for number in parsed
list.append(times, number)
big-time = text.to-int(text.join(_tokens(line), "")) try
elif text.starts-with(line, "Distance:")
let parsed = _numbers(line) try
for number in parsed
list.append(distances, number)
big-record = text.to-int(text.join(_tokens(line), "")) try
Sheet(times, distances, big-time, big-record)
# How many hold times beat one race's record; the parabola t * (T - t)
# rises then falls, so the winning holds are one contiguous run.
word _wins(time: Int, best: Int) -> Int
var count = 0
for hold in range(1, time)
if hold * (time - hold) > best
count = count + 1
count
## The product over all races of their winning hold counts.
word part-one(sheet: Sheet) -> Int
var product = 1
for index in range(0, list.length(sheet.times))
product = product * _wins(sheet.times[index], sheet.distances[index])
product
## The winning hold count of the single huge race.
word part-two(sheet: Sheet) -> Int
_wins(sheet.big-time, sheet.big-record)
# Advent of Code 2023, day 6 — Wait For It.
# Reads the race sheet from stdin until end of input, prints both answers.
word main()
# shortcut: the sheet holds digits, spaces, and two colons, 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 sheet = parse(buffer.to-text(input)) try
print(part-one(sheet))
print(part-two(sheet))
Day 7Camel Cards
The input lists hands of five cards, each with a bid; hands order by type from five of a kind down to high card, with ties broken by comparing cards left to right. Each hand wins its bid times its rank in that ordering, weakest hand at rank 1. Part one asks for the total winnings across all hands. Part two turns every jack into a joker that counts as whichever card makes the hand's type strongest while comparing as the lowest card, and asks for the total winnings again.
Show solution
Output
6440 5905
# Advent of Code 2023, day 7 — Camel Cards (solution words). Each hand
# orders first by its type — five of a kind down to high card — then by its
# cards left to right, and wins its bid times its rank, weakest first. A
# hand becomes one Int score: the type tier shifted up five base-14 digits,
# plus one digit per card, so list.sort-by ranks weakest to strongest.
# Part 2 turns J into a joker: it acts as whichever card makes the type
# best (tried one label at a time) while comparing as the lowest card.
## One hand: its five cards and its bid.
type Hand = record
cards: String
bid: Int
# How many times one label occurs in a five-card hand.
word _count(cards: String, label: String) -> Int
var count = 0
for index in range(0, 5)
if text.slice(cards, index, index + 1) == label
count = count + 1
count
# The hand's type tier on the cards as dealt: six for five of a kind down
# to zero for high card. Counting how many labels occur 0 to 5 times keeps
# the seven tiers a bucket check each.
word _tier(cards: String) -> Int
let buckets: List<Int> = []
for _ in range(0, 6)
list.append(buckets, 0)
for index in range(0, 13)
let label = text.slice("AKQJT98765432", index, index + 1)
let count = _count(cards, label)
buckets[count] = buckets[count] + 1
if buckets[5] == 1
6
elif buckets[4] == 1
5
elif buckets[3] == 1 and buckets[2] == 1
4
elif buckets[3] == 1
3
elif buckets[2] == 2
2
elif buckets[2] == 1
1
else
0
# The best tier the jokers can reach: every non-joker label is tried as
# their stand-in, so even five jokers land on five of a kind.
word _joker-tier(cards: String) -> Int
var best = 0
for index in range(0, 12)
let label = text.slice("AKQT98765432", index, index + 1)
let tier = _tier(text.replace(cards, "J", label))
if tier > best
best = tier
best
# One card's comparison digit within the order, highest card first.
word _card-value(card: String, order: String) -> Int
13 - text.index-of(order, card)
# The hand's whole ordering as one Int: tier first, then five base-14
# card digits.
word _score(cards: String, jokers: Bool) -> Int
let order = if jokers
"AKQT98765432J"
else
"AKQJT98765432"
let tier = if jokers
_joker-tier(cards)
else
_tier(cards)
var score = tier
for index in range(0, 5)
score = score * 14 + _card-value(text.slice(cards, index, index + 1), order)
score
## Parse the hands and their bids.
word parse(text: String) -> List<Hand>
let hands: List<Hand> = []
for line in text.split(text, "\n")
if text.length(line) > 0
let parts = text.split(line, " ")
let bid = text.to-int(parts[1]) try
let added = list.append(hands, Hand(parts[0], bid))
hands
word _part-one-key(hand: Hand) -> Int
_score(hand.cards, false)
word _part-two-key(hand: Hand) -> Int
_score(hand.cards, true)
# The total winnings once the hands are ranked weakest first.
word _winnings(hands: List<Hand>) -> Int
var total = 0
for index, hand in hands
total = total + hand.bid * (index + 1)
total
## Sum every hand's bid times its rank, jacks in their usual place.
word part-one(hands: List<Hand>) -> Int
_winnings(list.sort-by(hands, _part-one-key(_)))
## The same sum once jacks are jokers: best possible type, lowest card.
word part-two(hands: List<Hand>) -> Int
_winnings(list.sort-by(hands, _part-two-key(_)))
# Advent of Code 2023, day 7 — Camel Cards.
# Reads the hands from stdin until end of input, prints both answers.
word main()
# shortcut: a hand line holds card labels, one space, and 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 hands = parse(buffer.to-text(input)) try
print(part-one(hands))
print(part-two(hands))
Day 8Haunted Wasteland
The input gives one line of left and right instructions, then a network of named nodes, each mapping to the two nodes its left and right sides lead to. Walking from node AAA by the instructions, starting them over whenever they run out, the goal is to reach node ZZZ. Part one asks how many steps the walk takes. Part two walks from every node ending in A at once and asks how many steps pass before every walker stands on a node ending in Z at the same time.
Show solution
Output
2 2
# Advent of Code 2023, day 8 — Haunted Wasteland (solution words). One
# line of left/right instructions walks a network of three-letter nodes,
# each naming its left and right neighbors; the instructions start over
# whenever they run out. Part 1 counts the steps from AAA to ZZZ. Part 2
# starts at every node ending in A at once and needs all walkers on nodes
# ending in Z together — each walker cycles after its first Z, so the
# answer is the least common multiple of the cycle lengths (Euclid's gcd,
# hand-rolled: the language has no gcd or lcm word yet).
## One junction: where its left and right sides lead.
type Junction = record
left: String
right: String
## The network: the instructions and the junctions by name.
type Network = record
directions: String
nodes: Map<String, Junction>
## Parse the instruction line and every "NAME = (LEFT, RIGHT)" junction.
word parse(text: String) -> Network
var directions = ""
let nodes: Map<String, Junction> = {}
for line in text.split(text, "\n")
if text.length(line) > 0
if text.length(directions) == 0
directions = line
elif text.contains(line, "=")
let placed = map.put(nodes, text.slice(line, 0, 3), Junction(text.slice(line, 7, 10), text.slice(line, 12, 15)))
Network(directions, nodes)
# Where one step from a name leads: its left or right neighbor.
word _neighbor(nodes: Map<String, Junction>, name: String, letter: String) -> String
var result = name
match nodes[name]
case Option.Some(junction)
if letter == "L"
result = junction.left
else
result = junction.right
case Option.None
result = name
result
## The steps the single walk from AAA needs to reach ZZZ.
word part-one(network: Network) -> Int
var current = "AAA"
var steps = 0
var turn = 0
while current != "ZZZ"
current = _neighbor(network.nodes, current, text.slice(network.directions, turn, turn + 1))
steps = steps + 1
turn = turn + 1
if turn == text.length(network.directions)
turn = 0
steps
# The steps one walker needs to reach its first node ending in Z.
word _ghost-length(network: Network, start: String) -> Int
var current = start
var steps = 0
var turn = 0
while not text.ends-with(current, "Z")
current = _neighbor(network.nodes, current, text.slice(network.directions, turn, turn + 1))
steps = steps + 1
turn = turn + 1
if turn == text.length(network.directions)
turn = 0
steps
# Euclid's algorithm; the language ships no gcd word.
word _gcd(a: Int, b: Int) -> Int
var x = a
var y = b
while y > 0
let older = y
y = x % y
x = older
x
word _lcm(a: Int, b: Int) -> Int
a / _gcd(a, b) * b
## The step count at which every A-starting walker sits on a Z node: the
## least common multiple of the walkers' cycle lengths.
word part-two(network: Network) -> Int
var answer = 1
for name, junction in network.nodes
if text.ends-with(name, "A")
answer = _lcm(answer, _ghost-length(network, name))
answer
# The reason the input cannot be walked, or "" when it can. Guards against
# empty or truncated input so the walk cannot stall on a missing node.
word guard(network: Network) -> String
if map.length(network.nodes) == 0
"no network in input"
elif text.length(network.directions) == 0
"no instruction line in input"
elif not map.contains(network.nodes, "AAA")
"node AAA is missing from the network"
else
var problem = ""
for name, junction in network.nodes
for side in [junction.left, junction.right]
if text.length(problem) == 0 and not map.contains(network.nodes, side)
problem = "node " + name + " names missing neighbor " + side
problem
# Advent of Code 2023, day 8 — Haunted Wasteland.
# Reads the network from stdin until end of input, prints both answers.
word main()
# The network separates its instructions from its junctions 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 and 6-7 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 network = parse(buffer.to-text(input))
let problem = guard(network)
if text.length(problem) > 0
print(problem)
else
print(part-one(network))
print(part-two(network))
Day 9Mirage Maintenance
Each input line is a history of numbers. Repeatedly writing the differences between neighboring values builds shorter sequences down to all zeroes, and the history's next value is worked back up from there. Part one asks for the sum of the next values over all histories. Part two asks instead for the sum of the previous values, the numbers the same ladders place before each history's first value.
Show solution
Output
114 2
# Advent of Code 2023, day 9 — Mirage Maintenance (solution words). Each
# history becomes its sequence of neighboring differences, then that
# sequence's differences, down to all zeroes; the extrapolations work back
# up that ladder. The next value (part 1) adds each level's last number on
# the way down; the previous value (part 2) subtracts each level's first
# number instead. Both are one while per history — no recursion, so the
# call-depth limit never matters.
## Parse every history into its numbers.
word parse(text: String) -> List<List<Int>>
let histories: List<List<Int>> = []
for line in text.split(text, "\n")
if text.length(line) > 0
let history: List<Int> = []
for token in text.split(line, " ")
if text.length(token) > 0
let added = list.append(history, text.to-int(token) try)
let added = list.append(histories, history)
histories
word _nonzero(value: Int) -> Bool
value != 0
# One rung down the ladder: the differences of neighboring values.
word _differences(values: List<Int>) -> List<Int>
let next: List<Int> = []
for index in range(0, list.length(values) - 1)
list.append(next, values[index + 1] - values[index])
next
## The sum over all histories of the next value: every level's last number
## on the way down adds in.
word part-one(histories: List<List<Int>>) -> Int
var total = 0
for history in histories
var level = history
var next = 0
while list.any(level, _nonzero(_))
next = next + level[list.length(level) - 1]
level = _differences(level)
total = total + next
total
## The sum over all histories of the previous value: each level's first
## number, collected on the way down and folded from the bottom up as
## first minus the value below it.
word part-two(histories: List<List<Int>>) -> Int
var total = 0
for history in histories
let firsts: List<Int> = []
var level = history
while list.any(level, _nonzero(_))
list.append(firsts, level[0])
level = _differences(level)
var previous = 0
for index in range(0, list.length(firsts))
previous = firsts[list.length(firsts) - 1 - index] - previous
total = total + previous
total
# Advent of Code 2023, day 9 — Mirage Maintenance.
# Reads the histories from stdin until end of input, prints both answers.
word main()
# shortcut: a history line holds signed numbers and spaces, 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 histories = parse(buffer.to-text(input)) try
print(part-one(histories))
print(part-two(histories))
Day 10Pipe Maze
The input sketches a grid of pipe tiles, where each pipe shape joins two of the four directions and S marks the animal's starting tile; one continuous loop of pipe runs through the grid. Part one asks how many steps along the loop lie between S and the loop tile farthest from it. Part two asks how many tiles the loop fully encloses, counting ground tiles a fly could not escape from, with pipes outside the loop counted as ground.
Show solution
Output
4 1
# Advent of Code 2023, day 10 — Pipe Maze (solution words). The grid's
# pipes hold one continuous loop through the start tile S; part 1 is half
# the loop's length once S's two connections name its true shape. Part 2
# counts the tiles the loop encloses with a horizontal even-odd ray cast
# per row: a loop tile crosses the ray when it is a vertical pipe or a
# corner opening north (|, L, J), so an F..7 or L..J pair along the row
# nets zero crossings while F..J and L..7 net one — the tile is inside
# when the tiles left of it cross an odd number of times.
## The start tile's position.
type Start = record
x: Int
y: Int
## Parse the sketch 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 grid's width: its widest row.
word _width(grid: List<String>) -> Int
var widest = 0
for row in grid
if text.length(row) > widest
widest = text.length(row)
widest
# The tile at a position; ground beyond every edge.
word _tile(grid: List<String>, x: Int, y: Int) -> String
if y < 0 or y >= list.length(grid) or x < 0 or x >= text.length(grid[y])
"."
else
text.slice(grid[y], x, x + 1)
word _dx(direction: Int) -> Int
if direction == 1
1
elif direction == 3
-1
else
0
word _dy(direction: Int) -> Int
if direction == 2
1
elif direction == 0
-1
else
0
# Whether the tile a step in some direction connects back the way it came:
# a north step needs a south-opening neighbor (| 7 F), a south step a
# north-opening one (| L J), and an east or west step an east-west-opening one.
word _connects-back(tile: String, direction: Int) -> Bool
if direction == 1
text.contains("-7J", tile)
elif direction == 3
text.contains("-LF", tile)
elif direction == 0
text.contains("|7F", tile)
else
text.contains("|LJ", tile)
# Where the loop leaves a tile it was entered moving in some direction:
# the opening the shape did not use.
word _step-dir(tile: String, moving: Int) -> Int
let entered = (moving + 2) % 4
if tile == "|"
if entered == 0
2
else
0
elif tile == "-"
if entered == 1
3
else
1
elif tile == "L"
if entered == 0
1
else
0
elif tile == "J"
if entered == 0
3
else
0
elif tile == "7"
if entered == 2
3
else
2
else
if entered == 1
2
else
1
# The start tile's position.
word _start(grid: List<String>) -> Start
var found-x = 0
var found-y = 0
var found = false
var y = 0
while not found and y < list.length(grid)
let x = text.index-of(grid[y], "S")
if x >= 0
found = true
found-x = x
found-y = y
y = y + 1
Start(found-x, found-y)
# The two directions S connects over, in direction order 0..3 (N, E, S, W).
word _s-dirs(grid: List<String>) -> List<Int>
let dirs: List<Int> = []
let start = _start(grid)
for direction in range(0, 4)
if _connects-back(_tile(grid, start.x + _dx(direction), start.y + _dy(direction)), direction)
let added = list.append(dirs, direction)
dirs
# The pipe shape S stands in for, from its two connections.
word _s-shape(grid: List<String>) -> String
let dirs = _s-dirs(grid)
let a = dirs[0]
let b = dirs[1]
if a == 0
if b == 1
"L"
elif b == 2
"|"
else
"J"
elif a == 1
if b == 2
"F"
else
"-"
else
"7"
# A flat marker grid: one per loop tile, zero elsewhere.
word _marks(grid: List<String>) -> List<Int>
let width = _width(grid)
let marks: List<Int> = []
for _ in range(0, width * list.length(grid))
list.append(marks, 0)
let start = _start(grid)
marks[start.y * width + start.x] = 1
var direction = _s-dirs(grid)[0]
var x = start.x
var y = start.y
var done = false
while not done
x = x + _dx(direction)
y = y + _dy(direction)
if x == start.x and y == start.y
done = true
else
marks[y * width + x] = 1
direction = _step-dir(_tile(grid, x, y), direction)
marks
## Half the loop's length: the distance to the farthest tile either way.
word part-one(grid: List<String>) -> Int
var loop-tiles = 0
for mark in _marks(grid)
loop-tiles = loop-tiles + mark
loop-tiles / 2
# One row with S drawn as its true shape, for the ray cast.
word _row-text(grid: List<String>, y: Int) -> String
let start = _start(grid)
if y == start.y
let row = grid[y]
text.slice(row, 0, start.x) + _s-shape(grid) + text.slice(row, start.x + 1, text.length(row))
else
grid[y]
## How many tiles the loop encloses: odd crossings left of a ground tile.
word part-two(grid: List<String>) -> Int
let width = _width(grid)
let marks = _marks(grid)
var inside = 0
for y in range(0, list.length(grid))
let row = _row-text(grid, y)
for x in range(0, text.length(row))
if marks[y * width + x] == 0
var crossings = 0
for scan in range(0, x)
if marks[y * width + scan] == 1 and text.contains("|LJ", text.slice(row, scan, scan + 1))
crossings = crossings + 1
if crossings % 2 == 1
inside = inside + 1
inside
# Advent of Code 2023, day 10 — Pipe Maze.
# Reads the pipe sketch from stdin until end of input, prints both answers.
word main()
# shortcut: a sketch row holds pipe shapes, dots, and the S marker, 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 grid = parse(buffer.to-text(input))
print(part-one(grid))
print(part-two(grid))
Day 11Cosmic Expansion
The input is a grid of empty space and galaxies, and every row or column holding no galaxy doubles in size before any distance is measured. Part one asks for the sum of the shortest path lengths between every pair of galaxies on the expanded grid. Part two replaces the doubling with a one-million-fold expansion of each empty row or column and asks for the same sum.
Show solution
Output
374 82000210
# Advent of Code 2023, day 11 — Cosmic Expansion (solution words).
# The image holds galaxies on a grid whose empty rows and columns expand
# before any distance is measured. Materializing the expanded grid is
# hopeless at part 2's million-fold expansion, so each empty row and column
# is a flag instead: a pair's distance is its Manhattan walk plus the extra
# per empty line crossed, and the extra is 1 in part 1 and 999999 in part 2.
type Galaxy = record
row: Int
col: Int
type Universe = record
galaxies: List<Galaxy>
row-empty: List<Bool>
col-empty: List<Bool>
# The absolute value of an integer.
word _abs(value: Int) -> Int
if value < 0
0 - value
else
value
# The count of empty lines strictly between two coordinates.
word _gaps(empty: List<Bool>, a: Int, b: Int) -> Int
var low = a
var high = b
if low > high
low = b
high = a
var count = 0
for index in range(low, high)
if empty[index]
count = count + 1
count
## Parse the image into galaxies plus its empty-row and empty-column flags.
word parse(text: String) -> Universe
let rows: List<String> = []
for line in text.split(text, "\n")
if text.length(line) > 0
let added = list.append(rows, line)
let width = text.length(rows[0])
let galaxies: List<Galaxy> = []
let row-empty: List<Bool> = []
for r in range(0, list.length(rows))
let row = rows[r]
var empty = true
for c in range(0, width)
if text.slice(row, c, c + 1) == "#"
list.append(galaxies, Galaxy(r, c))
empty = false
list.append(row-empty, empty)
let col-empty: List<Bool> = []
for c in range(0, width)
var empty = true
for r in range(0, list.length(rows))
if text.slice(rows[r], c, c + 1) == "#"
empty = false
list.append(col-empty, empty)
Universe(galaxies, row-empty, col-empty)
# The sum of pairwise distances, each empty line crossed adding extra.
word _expand-total(universe: Universe, extra: Int) -> Int
var total = 0
let n = list.length(universe.galaxies)
for i in range(0, n)
let a = universe.galaxies[i]
for j in range(i + 1, n)
let b = universe.galaxies[j]
let walk = _abs(a.row - b.row) + _abs(a.col - b.col)
let gaps = _gaps(universe.row-empty, a.row, b.row) + _gaps(universe.col-empty, a.col, b.col)
total = total + walk + extra * gaps
total
## Sum the pairwise distances with empty lines doubled.
word part-one(universe: Universe) -> Int
_expand-total(universe, 1)
## Sum the pairwise distances with empty lines a million times as wide.
word part-two(universe: Universe) -> Int
_expand-total(universe, 999999)
# Advent of Code 2023, day 11 — Cosmic Expansion.
# Reads the image from stdin until end of input, prints both answers.
word main()
# shortcut: the image holds dots and hashes only, 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 universe = parse(buffer.to-text(input))
print(part-one(universe))
print(part-two(universe))
Day 12Hot Springs
Each input line shows a row of springs — . operational, # damaged, ? unknown — followed by the sizes of the damaged-spring groups in the order they appear. Part one asks for the total number of ways to fill in the unknown springs so every row matches its list of group sizes. Part two unfolds each row fivefold, joining copies with a ?, and repeats its group sizes to match, and asks for the same total over the unfolded rows.
Show solution
Output
21 525152
# Advent of Code 2023, day 12 — Hot Springs (solution words).
# Each line is a row of springs plus the sizes of its damaged groups. The
# arrangement count is a flat dynamic program over (prefix length, groups
# placed): a cell holds how many ways explain the prefix so far; a '.' or
# '?' steps one position as a dot, and a '#' or '?' may place the next
# group where the row fits it plus its trailing separator. Part 2 unfolds
# the row and its groups fivefold, joining copies with '?', and the same
# table answers it — no recursion, so the 256-deep call limit never dips.
type Row = record
springs: String
groups: List<Int>
## Parse the condition records into spring rows and their group sizes.
word parse(text: String) -> List<Row>
let rows: List<Row> = []
for line in text.split(text, "\n")
if text.length(line) > 0
let halves = text.split(line, " ")
let groups: List<Int> = []
for token in text.split(halves[1], ",")
list.append(groups, text.to-int(token) try)
let added = list.append(rows, Row(halves[0], groups))
rows
# The number of ways one spring row matches its group sizes.
word _count(springs: String, groups: List<Int>) -> Int
let n = text.length(springs)
let g = list.length(groups)
let stride = g + 1
let cells = (n + 1) * stride
let table: List<Int> = []
for index in range(0, cells)
list.append(table, 0)
table[0] = 1
for i in range(0, n)
let ch = text.slice(springs, i, i + 1)
let here = i * stride
for j in range(0, stride)
let ways = table[here + j]
if ways > 0
if ch == "." or ch == "?"
table[here + stride + j] = table[here + stride + j] + ways
if ch == "#" or ch == "?"
if j < g
let size = groups[j]
if i + size <= n
var fits = true
for k in range(i, i + size)
if text.slice(springs, k, k + 1) == "."
fits = false
if fits
if i + size == n
table[cells - stride + j + 1] = table[cells - stride + j + 1] + ways
else
let after = text.slice(springs, i + size, i + size + 1)
if after == "." or after == "?"
let next = (i + size + 1) * stride + j + 1
table[next] = table[next] + ways
table[cells - 1]
# The row unfolded fivefold, its groups repeated to match.
word _unfold(row: Row) -> Row
let parts: List<String> = []
let groups: List<Int> = []
for copy in range(0, 5)
list.append(parts, row.springs)
for size in row.groups
list.append(groups, size)
Row(text.join(parts, "?"), groups)
## Sum the arrangement counts of every row as given.
word part-one(rows: List<Row>) -> Int
var total = 0
for row in rows
total = total + _count(row.springs, row.groups)
total
## Sum the arrangement counts of every row unfolded fivefold.
word part-two(rows: List<Row>) -> Int
var total = 0
for row in rows
let big = _unfold(row)
total = total + _count(big.springs, big.groups)
total
# Advent of Code 2023, day 12 — Hot Springs.
# Reads the condition records from stdin until end of input, prints both
# answers.
word main()
# shortcut: the records hold dots, hashes, question marks, digits, spaces,
# and commas only, 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 records = parse(buffer.to-text(input)) try
print(part-one(records))
print(part-two(records))
Day 13Point of Incidence
The input holds grids of ash and rocks, one pattern per block, and each pattern has a reflection line between two rows or between two columns with one side matching the other exactly. Part one asks for a summary number: the columns left of each vertical reflection, plus 100 times the rows above each horizontal reflection, added over all patterns. Part two fixes exactly one smudged cell per pattern — ash where rock should be or the reverse — and asks for the same summaries over the new reflection each cleaned pattern has.
Show solution
Output
405 400
# Advent of Code 2023, day 13 — Point of Incidence (solution words).
# Each pattern is a block of ash-and-rock rows. A mirror between rows i-1
# and i holds when every facing pair across the fold matches, and the
# summary counts the rows above it. Both parts scan the same candidates
# and count mismatched cells across the fold: part 1 accepts the perfect
# fold, part 2 the fold with exactly one mismatched cell pair — the one
# smudge flipped. Vertical mirrors are the same scan over the transposed
# pattern, so one helper answers every direction.
type Pattern = record
rows: List<String>
## Parse the ash-and-rock patterns, one block per blank-separated group.
word parse(text: String) -> List<Pattern>
let patterns: List<Pattern> = []
var rows: List<String> = []
for line in text.split(text, "\n")
if text.length(line) > 0
let added = list.append(rows, line)
elif list.length(rows) > 0
list.append(patterns, Pattern(rows))
rows = []
if list.length(rows) > 0
let added = list.append(patterns, Pattern(rows))
patterns
# The pattern turned a quarter turn, so column mirrors become row mirrors.
word _transpose(rows: List<String>) -> List<String>
let turned: List<String> = []
for c in range(0, text.length(rows[0]))
var column = ""
for r in range(0, list.length(rows))
column = column + text.slice(rows[r], c, c + 1)
list.append(turned, column)
turned
# The first mirror position with exactly the wanted mismatched-cell count
# across its fold, zero when no fold qualifies.
word _mirror(rows: List<String>, want: Int) -> Int
var result = 0
for i in range(1, list.length(rows))
var bad = 0
var a = i - 1
var b = i
while a >= 0 and b < list.length(rows) and bad <= want
let top = rows[a]
let bottom = rows[b]
for c in range(0, text.length(top))
if text.slice(top, c, c + 1) != text.slice(bottom, c, c + 1)
bad = bad + 1
a = a - 1
b = b + 1
if bad == want and result == 0
result = i
result
## Sum the summaries of every pattern's perfect mirror.
word part-one(patterns: List<Pattern>) -> Int
var total = 0
for pattern in patterns
let turned = _transpose(pattern.rows)
total = total + 100 * _mirror(pattern.rows, 0) + _mirror(turned, 0)
total
## Sum the summaries of every pattern's one-smudge mirror.
word part-two(patterns: List<Pattern>) -> Int
var total = 0
for pattern in patterns
let turned = _transpose(pattern.rows)
total = total + 100 * _mirror(pattern.rows, 1) + _mirror(turned, 1)
total
# Advent of Code 2023, day 13 — Point of Incidence.
# Reads the patterns from stdin until end of input, prints both answers.
word main()
# The patterns separate with blank lines, 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 11-12 use cannot cover
# 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 patterns = parse(buffer.to-text(input))
print(part-one(patterns))
print(part-two(patterns))
Day 14Parabolic Reflector Dish
The input is a platform grid holding rounded rocks, cube-shaped rocks, and empty spaces. Tilting the platform north rolls every rounded rock upward until another rock or the edge stops it, while cube-shaped rocks never move. Part one asks for the total load on the north support beam after that tilt, where each rounded rock loads the beam by the count of rows from it to the platform's south edge, its own row included. Part two spins the platform through a billion north-west-south-east tilt cycles and asks for the load after the last cycle.
Show solution
Output
136 64
# Advent of Code 2023, day 14 — Parabolic Reflector Dish (solution words).
# Rounded rocks roll until something stops them, and a tilt acts on whole
# lines at a time: transpose the grid, slide each column-line's rocks into
# the gaps between cube rocks (`_tilt-line` rebuilds every # separated
# segment rocks-first), transpose back. A spin is four of those with a
# quarter turn between, and part 2's billion spins never run — the joined
# grid is remembered in a Map, and once a state repeats, the remaining
# spins jump over whole cycles to the state the billionth lands on.
type Dish = record
grid: List<String>
## Parse the platform grid.
word parse(text: String) -> Dish
let grid: List<String> = []
for line in text.split(text, "\n")
if text.length(line) > 0
let added = list.append(grid, line)
Dish(grid)
# n copies of a one-character string joined.
word _repeat(ch: String, n: Int) -> String
var out = ""
for index in range(0, n)
out = out + ch
out
# One line with its rounded rocks slid to the line's start.
word _tilt-line(line: String) -> String
var out = ""
var rocks = 0
var dots = 0
for index in range(0, text.length(line))
let ch = text.slice(line, index, index + 1)
if ch == "#"
out = out + _repeat("O", rocks) + _repeat(".", dots) + "#"
rocks = 0
dots = 0
elif ch == "O"
rocks = rocks + 1
else
dots = dots + 1
out = out + _repeat("O", rocks) + _repeat(".", dots)
out
# The grid turned a quarter turn clockwise.
word _rotate(grid: List<String>) -> List<String>
let turned: List<String> = []
for c in range(0, text.length(grid[0]))
var column = ""
for r in range(0, list.length(grid))
column = column + text.slice(grid[list.length(grid) - 1 - r], c, c + 1)
list.append(turned, column)
turned
# The grid's rows read as columns.
word _transpose(grid: List<String>) -> List<String>
let turned: List<String> = []
for c in range(0, text.length(grid[0]))
var column = ""
for r in range(0, list.length(grid))
column = column + text.slice(grid[r], c, c + 1)
list.append(turned, column)
turned
# The grid with every column tilted north.
word _tilt-north(grid: List<String>) -> List<String>
let columns: List<String> = []
let source = _transpose(grid)
for index in range(0, list.length(source))
list.append(columns, _tilt-line(source[index]))
_transpose(columns)
# The grid after one north-west-south-east spin.
word _spin(grid: List<String>) -> List<String>
var current = grid
for side in range(0, 4)
current = _tilt-north(current)
current = _rotate(current)
current
# The total load: each rounded rock loads its rows from the south edge.
word _load(grid: List<String>) -> Int
let height = list.length(grid)
var total = 0
for r in range(0, height)
let row = grid[r]
for c in range(0, text.length(row))
if text.slice(row, c, c + 1) == "O"
total = total + height - r
total
# The iteration a grid state was first seen at, -1 when never.
word _seen-at(seen: Map<String, Int>, key: String) -> Int
match seen[key]
case Option.Some(start)
start
case Option.None
-1
## The load on the north support beam after one north tilt.
word part-one(dish: Dish) -> Int
_load(_tilt-north(dish.grid))
## The load after a billion north-west-south-east spins.
word part-two(dish: Dish) -> Int
let seen: Map<String, Int> = {}
var grid = dish.grid
var it = 0
let target = 1000000000
while it < target
let key = text.join(grid, "\n")
let start = _seen-at(seen, key)
if start < 0
let stored = map.put(seen, key, it)
let jump = if start >= 0
let cycle = it - start
let remaining = target - it
(remaining / cycle) * cycle
else
0
it = it + jump
# an exact-division jump already lands on the target grid
if it < target
grid = _spin(grid)
it = it + 1
_load(grid)
# Advent of Code 2023, day 14 — Parabolic Reflector Dish.
# Reads the platform from stdin until end of input, prints both answers.
word main()
# shortcut: the platform holds dots, hashes, and capital O rocks only, 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 dish = parse(buffer.to-text(input))
print(part-one(dish))
print(part-two(dish))
Day 15Lens Library
The input is one comma-separated sequence of steps. The HASH algorithm turns a step's characters into a number from 0 to 255 by adding each character's code, multiplying by 17, and keeping the remainder of dividing by 256. Part one asks for the sum of the HASH results over all steps. Part two runs each step as an operation on lens boxes: the HASH of a step's label picks its box, a trailing dash removes that label's lens, and a trailing = number replaces or appends the lens with that focal length; the answer sums every lens's box number, slot number, and focal length multiplied together.
Show solution
Output
1320 145
# Advent of Code 2023, day 15 — Lens Library (solution words).
# The HASH algorithm needs character codes and the language has no char
# type, so _code maps a one-character slice through index-of lookups on
# alphabet strings — the epic's known trap, paid once per character. Part
# 2 runs the steps as box operations on labeled lenses: '-' takes the
# label out of its box, '=' replaces the label's focal length or appends
# the lens at its box's end, and the answer sums each lens's box, slot,
# and focal factors.
type Lens = record
label: String
focal: Int
# shortcut: the step grammar is lowercase letters, digits, =, and - only;
# widen _code if an input ever uses other characters
word _code(ch: String) -> Int
let letter = text.index-of("abcdefghijklmnopqrstuvwxyz", ch)
if letter >= 0
letter + 97
else
let digit = text.index-of("0123456789", ch)
if digit >= 0
digit + 48
elif ch == "="
61
else
45
# The HASH of a step: each character's code added, times 17, remainder 256.
word _hash(step: String) -> Int
var value = 0
for index in range(0, text.length(step))
value = (value + _code(text.slice(step, index, index + 1))) * 17 % 256
value
## Parse the comma-separated initialization sequence into its steps.
word parse(text: String) -> List<String>
text.split(text.replace(text, "\n", ""), ",")
# The box without one label, unchanged when the label is absent.
word _without(box: List<Lens>, label: String) -> List<Lens>
let keep: List<Lens> = []
for lens in box
if lens.label != label
let added = list.append(keep, lens)
keep
# The box after one = step: the label's focal length replaced in place,
# or the lens appended when the box does not hold it yet.
word _upsert(box: List<Lens>, label: String, focal: Int) -> List<Lens>
var done = false
for index in range(0, list.length(box))
let lens = box[index]
if not done and lens.label == label
box[index] = Lens(label, focal)
done = true
if not done
let added = list.append(box, Lens(label, focal))
box
## Sum the HASH of every step.
word part-one(steps: List<String>) -> Int
var total = 0
for step in steps
total = total + _hash(step)
total
## Run the box operations over 256 boxes and sum the focusing power.
word part-two(steps: List<String>) -> Int
let boxes: List<List<Lens>> = []
for index in range(0, 256)
let fresh: List<Lens> = []
list.append(boxes, fresh)
for step in steps
if text.ends-with(step, "-")
let label = text.slice(step, 0, text.length(step) - 1)
let box-number = _hash(label)
boxes[box-number] = _without(boxes[box-number], label)
else
let halves = text.split(step, "=")
let label = halves[0]
let focal = text.to-int(halves[1]) try
let box-number = _hash(label)
boxes[box-number] = _upsert(boxes[box-number], label, focal)
var total = 0
for box-number in range(0, 256)
let box = boxes[box-number]
for slot in range(0, list.length(box))
let lens = box[slot]
total = total + (box-number + 1) * (slot + 1) * lens.focal
total
# Advent of Code 2023, day 15 — Lens Library.
# Reads the initialization sequence from stdin until end of input, prints
# both answers.
word main()
# shortcut: the sequence holds lowercase letters, digits, equals, dashes,
# commas, and newlines only, 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 steps = parse(buffer.to-text(input))
print(part-one(steps))
print(part-two(steps) try)
Day 16The Floor Will Be Lava
The input is a grid of empty space, mirrors, and splitters, and one beam enters at the top left heading right, reflecting off mirrors and splitting in two at the flat side of a splitter. Part one asks how many tiles end up energized, meaning at least one beam passes, reflects, or splits there. Part two tries a beam from every tile on the grid's edge heading inward and asks for the largest energized count any entry reaches.
Show solution
Output
46 51
# Advent of Code 2023, day 16 — The Floor Will Be Lava (solution words).
# A beam walks the grid of mirrors and splitters; a tile is energized when
# any beam passes through it. The walk is an iterative worklist of
# (x, y, direction) states — directions are ints 0-3 (N, E, S, W) — with a
# Map of already-seen states: a beam that re-enters a tile the same way
# repeats forever, so seen states are skipped and the worklist drains.
# Part 2 restarts the walk from every edge tile heading inward and keeps
# the largest energized count.
## Parse the layout 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
word _dx(direction: Int) -> Int
if direction == 1
1
elif direction == 3
-1
else
0
word _dy(direction: Int) -> Int
if direction == 2
1
elif direction == 0
-1
else
0
# The tile at a position; empty space beyond every edge.
word _tile(grid: List<String>, x: Int, y: Int) -> String
if y < 0 or y >= list.length(grid) or x < 0 or x >= text.length(grid[y])
"."
else
text.slice(grid[y], x, x + 1)
# The direction(s) a beam leaves a tile it entered moving in some
# direction: mirrors turn 90 degrees, splitters split a beam that hits
# their flat side, and everything else passes through.
word _leaving(tile: String, moving: Int) -> List<Int>
let dirs: List<Int> = []
if tile == "/"
list.append(dirs, [1, 0, 3, 2][moving])
elif tile == "\\"
list.append(dirs, [3, 2, 1, 0][moving])
elif tile == "|" and (moving == 1 or moving == 3)
list.append(dirs, 0)
list.append(dirs, 2)
elif tile == "-" and (moving == 0 or moving == 2)
list.append(dirs, 1)
list.append(dirs, 3)
else
list.append(dirs, moving)
dirs
# How many tiles one beam starting at (sx, sy) heading sd energizes: the
# worklist holds x, y, direction triples consumed by a head index, the
# seen map stops repeated states, and the lit map counts tiles.
word _energized(grid: List<String>, sx: Int, sy: Int, sd: Int) -> Int
let seen: Map<String, Bool> = {}
let lit: Map<String, Bool> = {}
let work: List<Int> = []
list.append(work, sx)
list.append(work, sy)
list.append(work, sd)
var head = 0
while head < list.length(work)
let x = work[head]
let y = work[head + 1]
let d = work[head + 2]
head = head + 3
let state = x + "," + y + "," + d
if x >= 0 and y >= 0 and y < list.length(grid) and x < text.length(grid[y]) and not map.contains(seen, state)
seen[state] = true
lit[x + "," + y] = true
for next in _leaving(_tile(grid, x, y), d)
list.append(work, x + _dx(next))
list.append(work, y + _dy(next))
list.append(work, next)
map.length(lit)
## Tiles energized by the beam entering the top left heading right.
word part-one(grid: List<String>) -> Int
_energized(grid, 0, 0, 1)
## The largest energized count over every edge entry heading inward:
# left column heading east, right column heading west, top row heading
# south, bottom row heading north.
word part-two(grid: List<String>) -> Int
let width = text.length(grid[0])
let height = list.length(grid)
var best = 0
for y in range(0, height)
let west = _energized(grid, 0, y, 1)
let east = _energized(grid, width - 1, y, 3)
if west > best
best = west
if east > best
best = east
for x in range(0, width)
let north = _energized(grid, x, 0, 2)
let south = _energized(grid, x, height - 1, 0)
if north > best
best = north
if south > best
best = south
best
# Advent of Code 2023, day 16 — The Floor Will Be Lava.
# Reads the layout from stdin until end of input, prints both answers.
word main()
# shortcut: a layout row holds only ./\|- characters, 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 grid = parse(buffer.to-text(input))
print(part-one(grid))
print(part-two(grid))
Day 17Clumsy Crucible
The input is a grid of digits, each digit the heat loss of entering that city block, with the crucible starting at the top left and the factory at the bottom right. The crucible can go at most three blocks in one direction before it must turn left or right, and it never reverses. Part one asks for the least total heat loss of any route obeying those rules. Part two replaces it with an ultra crucible that must go at least four and at most ten blocks in a row before it may turn or stop, and asks for its least heat loss.
Show solution
Output
102 94
# Advent of Code 2023, day 17 — Clumsy Crucible (solution words). The
# least-heat route is Dijkstra over (x, y, direction, run) states — the
# run counts consecutive straight blocks, so the crucible's straight-line
# limits live in the state, not the cost. There is no priority-queue
# word, so the frontier is a Map<Int, Int> from packed state to cost and
# each step min-scans it; samples are small, so the repeated linear scan
# is the honest price. States pack into one Int (x*H+y, *4+direction,
# *11+run) so pops decode by division, not string parsing. Part 1 turns
# or continues freely up to three straight blocks; part 2's ultra
# crucible must run four to ten blocks straight and needs four behind it
# before it may stop at the factory.
## Parse the city into its rows of heat digits.
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 _dx(direction: Int) -> Int
if direction == 1
1
elif direction == 3
-1
else
0
word _dy(direction: Int) -> Int
if direction == 2
1
elif direction == 0
-1
else
0
# The heat loss of entering a block: its digit's place in 0..9.
word _heat(grid: List<String>, x: Int, y: Int) -> Int
text.index-of("0123456789", text.slice(grid[y], x, x + 1))
# Pack a Dijkstra state into one Int.
word _encode(x: Int, y: Int, direction: Int, run: Int, height: Int) -> Int
((x * height + y) * 4 + direction) * 11 + run
# The least heat loss under one pair of straight-run limits.
word _dijkstra(grid: List<String>, min-run: Int, max-run: Int) -> Int
let height = list.length(grid)
let width = text.length(grid[0])
let dist: Map<Int, Int> = {}
let frontier: Map<Int, Int> = {}
frontier[_encode(0, 0, 1, 0, height)] = 0
frontier[_encode(0, 0, 2, 0, height)] = 0
var answer = -1
var searching = true
while searching
if map.length(frontier) == 0
searching = false
else
# the cheapest frontier state by repeated min-scan
var best-key = 0
var best-cost = 0
var first = true
for key, cost in frontier
if first or cost < best-cost
best-key = key
best-cost = cost
first = false
map.remove(frontier, best-key)
let run = best-key % 11
let rest = best-key / 11
let direction = rest % 4
let y = rest / 4 % height
let x = rest / 4 / height
if x == width - 1 and y == height - 1 and run >= min-run
answer = best-cost
searching = false
else
for next in range(0, 4)
# never reverse, and below the minimum run only
# straight ahead (run 0 is the start, any way out)
if next != (direction + 2) % 4
var blocked = next != direction and run > 0 and run < min-run
var next-run = 1
if next == direction
next-run = run + 1
if next-run > max-run
blocked = true
if not blocked
let nx = x + _dx(next)
let ny = y + _dy(next)
if nx >= 0 and ny >= 0 and ny < height and nx < width
let next-cost = best-cost + _heat(grid, nx, ny)
let nkey = _encode(nx, ny, next, next-run, height)
let better = match dist[nkey]
case Option.Some(old)
next-cost < old
case Option.None
true
if better
dist[nkey] = next-cost
frontier[nkey] = next-cost
answer
## Least heat loss with at most three straight blocks in a row.
word part-one(grid: List<String>) -> Int
_dijkstra(grid, 1, 3)
## Least heat loss for the ultra crucible: four to ten straight blocks,
# and four behind it before it may stop.
word part-two(grid: List<String>) -> Int
_dijkstra(grid, 4, 10)
# Advent of Code 2023, day 17 — Clumsy Crucible.
# Reads the city grid from stdin until end of input, prints both answers.
word main()
# shortcut: a city row holds only 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 grid = parse(buffer.to-text(input))
print(part-one(grid))
print(part-two(grid))
Day 18Lavaduct Lagoon
The input is a dig plan of steps, each naming a direction and a distance in meters, and the steps trace one closed loop of trench. Part one asks how many cubic meters of lava the lagoon could hold once the loop's interior is dug out to one meter deep as well. Part two rereads each step's hex color code as the true instruction — the last digit names the direction and the first five the distance — and asks for the same volume on the much larger loop.
Show solution
Output
62 952408144115
# Advent of Code 2023, day 18 — Lavaduct Lagoon (solution words). The
# trench loop's volume is its interior plus the trench itself, both one
# meter deep, so the answer is the count of lattice points inside or on
# the loop: the shoelace formula gives the area, Pick's theorem trades
# it for interior-plus-boundary, and everything stays in integers — the
# doubled total (2*area + perimeter + 2) is always even, so one halving
# at the end is exact. Directions encode 0-3 as R, D, L, U, which is
# also what a hex color's last digit names; part 2 reads the first five
# hex digits as the distance.
## Both dig plans in one record: the listed steps, and the steps the
## hex colors encode.
type DigPlan = record
dirs: List<Int>
dists: List<Int>
hex-dirs: List<Int>
hex-dists: List<Int>
# One hex digit's value: its place in 0..f.
word _digit(ch: String) -> Int
text.index-of("0123456789abcdef", ch)
# The five hex digits naming a distance.
word _hex-length(color: String) -> Int
var value = 0
for at in range(2, 7)
value = value * 16 + _digit(text.slice(color, at, at + 1))
value
## Parse every "L N (#RRGGBB)" line into both plans; the sixth color
## digit names the direction (0 R, 1 D, 2 L, 3 U) and the first five
## the distance.
word parse(text: String) -> DigPlan
let dirs: List<Int> = []
let dists: List<Int> = []
let hex-dirs: List<Int> = []
let hex-dists: List<Int> = []
for line in text.split(text, "\n")
if text.length(line) > 0
let parts = text.split(line, " ")
list.append(dirs, text.index-of("RDLU", parts[0]))
list.append(dists, text.to-int(parts[1]) try)
list.append(hex-dirs, _digit(text.slice(parts[2], 7, 8)))
let added = list.append(hex-dists, _hex-length(parts[2]))
DigPlan(dirs, dists, hex-dirs, hex-dists)
word _step-x(direction: Int) -> Int
[1, 0, -1, 0][direction]
word _step-y(direction: Int) -> Int
[0, 1, 0, -1][direction]
word _abs(n: Int) -> Int
if n < 0
-n
else
n
# Interior plus boundary lattice points: shoelace for the area, Pick
# for the count, combined as (2*area + perimeter + 2) / 2.
word _area(dirs: List<Int>, dists: List<Int>) -> Int
var x = 0
var y = 0
var cross = 0
var perimeter = 0
for at in range(0, list.length(dirs))
let length = dists[at]
let next-x = x + _step-x(dirs[at]) * length
let next-y = y + _step-y(dirs[at]) * length
cross = cross + (x + next-x) * (y - next-y)
perimeter = perimeter + length
x = next-x
y = next-y
(_abs(cross) + perimeter + 2) / 2
## Lava volume following the listed steps.
word part-one(plan: DigPlan) -> Int
_area(plan.dirs, plan.dists)
## Lava volume following the steps the hex colors encode.
word part-two(plan: DigPlan) -> Int
_area(plan.hex-dirs, plan.hex-dists)
# Advent of Code 2023, day 18 — Lavaduct Lagoon.
# Reads the dig plan from stdin until end of input, prints both answers.
word main()
# shortcut: a plan line holds a letter, a number, and a parenthesized
# hex color, 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 plan = parse(buffer.to-text(input)) try
print(part-one(plan))
print(part-two(plan))
Day 19Aplenty
The input has two sections: workflows whose rules test a part's four ratings and send it to another workflow, to accept, or to reject, and then the ratings of the parts to sort. Every part starts at the workflow named in. Part one asks for the sum of all four ratings added over the parts that end up accepted. Part two asks how many distinct combinations of ratings — each rating ranging from 1 to 4000 — the workflows would accept.
Show solution
Output
19114 167409079868000
# Advent of Code 2023, day 19 — Aplenty (solution words). Parts walk
# the workflows from "in" until an A or R; part 1 sums the ratings of
# the parts that land on A. Part 2 asks how many of the 4000^4 rating
# combinations would be accepted, answered by carrying whole rating
# ranges through the workflows: each conditional rule splits its
# category's range into the piece that passes (sent to the rule's
# target) and the piece that fails (carried to the next rule), and an
# accepted fragment counts its volume, the product of its four span
# sizes. The recursion is the workflow chain, a handful of hops deep.
## One rule: a category index 0-3 (x, m, a, s), an operation 0 (<),
## 1 (>), or 2 (bare target), the comparison value, and where a match
## goes.
type Rule = record
cat: Int
op: Int
val: Int
target: String
## The sorter: workflows by name, and the parts to run.
type Sorter = record
workflows: Map<String, List<Rule>>
parts: List<List<Int>>
## Parse the workflow lines, the blank separator, and the part lines.
word parse(text: String) -> Sorter
let workflows: Map<String, List<Rule>> = {}
let parts: List<List<Int>> = []
var in-parts = false
for line in text.split(text, "\n")
if text.length(line) > 0
if in-parts
let ratings: List<Int> = []
for field in text.split(text.slice(line, 1, text.length(line) - 1), ",")
list.append(ratings, text.to-int(text.slice(field, 2, text.length(field))) try)
let added = list.append(parts, ratings)
else
let name = text.slice(line, 0, text.index-of(line, "{"))
let rules: List<Rule> = []
for piece in text.split(text.slice(line, text.index-of(line, "{") + 1, text.length(line) - 1), ",")
if text.contains(piece, ":")
let sides = text.split(piece, ":")
let cond = sides[0]
list.append(rules, Rule(text.index-of("xmas", text.slice(cond, 0, 1)), _op-of(cond), text.to-int(text.slice(cond, 2, text.length(cond))) try, sides[1]))
else
list.append(rules, Rule(0, 2, 0, piece))
workflows[name] = rules
else
in-parts = true
Sorter(workflows, parts)
# A condition's operation: 0 for <, 1 for >.
word _op-of(cond: String) -> Int
if text.contains(cond, "<")
0
else
1
# Where one part goes next: the first matching rule's target.
word _first-target(rules: List<Rule>, part: List<Int>) -> String
var target = "R"
var found = false
var at = 0
while not found and at < list.length(rules)
let rule = rules[at]
if rule.op == 2 or (rule.op == 0 and part[rule.cat] < rule.val) or (rule.op == 1 and part[rule.cat] > rule.val)
target = rule.target
found = true
at = at + 1
target
## The sum of all four ratings over the accepted parts.
word part-one(sorter: Sorter) -> Int
var total = 0
for part in sorter.parts
var current = "in"
while current != "A" and current != "R"
match sorter.workflows[current]
case Option.Some(rules)
current = _first-target(rules, part)
case Option.None
current = "R"
if current == "A"
for rating in part
total = total + rating
total
# A copy of the ranges with one slot replaced.
word _with(ranges: List<Int>, at: Int, value: Int) -> List<Int>
let copy: List<Int> = []
for index in range(0, list.length(ranges))
if index == at
list.append(copy, value)
else
list.append(copy, ranges[index])
copy
# An accepted fragment's volume: the product of its four span sizes.
word _volume(ranges: List<Int>) -> Int
var product = 1
for cat in range(0, 4)
product = product * (ranges[cat * 2 + 1] - ranges[cat * 2] + 1)
product
# Split one rule's category: pass the matching span to the target,
# carry the rest past the rule, and stop when nothing remains.
word _walk-rules(workflows: Map<String, List<Rule>>, rules: List<Rule>, at: Int, ranges: List<Int>) -> Int
if at >= list.length(rules)
0
else
let rule = rules[at]
if rule.op == 2
_count(workflows, rule.target, ranges)
else
var passing = ranges
var failing = ranges
if rule.op == 0
passing = _with(ranges, rule.cat * 2 + 1, rule.val - 1)
failing = _with(ranges, rule.cat * 2, rule.val)
else
passing = _with(ranges, rule.cat * 2, rule.val + 1)
failing = _with(ranges, rule.cat * 2 + 1, rule.val)
if passing[rule.cat * 2] > passing[rule.cat * 2 + 1]
_walk-rules(workflows, rules, at + 1, failing)
elif failing[rule.cat * 2] > failing[rule.cat * 2 + 1]
_count(workflows, rule.target, passing)
else
_count(workflows, rule.target, passing) + _walk-rules(workflows, rules, at + 1, failing)
# How many rating combinations in one fragment the workflows accept.
word _count(workflows: Map<String, List<Rule>>, current: String, ranges: List<Int>) -> Int
if current == "A"
_volume(ranges)
elif current == "R"
0
else
match workflows[current]
case Option.Some(rules)
_walk-rules(workflows, rules, 0, ranges)
case Option.None
0
## How many of the 4000^4 rating combinations are accepted.
word part-two(sorter: Sorter) -> Int
_count(sorter.workflows, "in", [1, 4000, 1, 4000, 1, 4000, 1, 4000])
# Advent of Code 2023, day 19 — Aplenty.
# Reads workflows and parts from stdin until end of input, prints both
# answers.
word main()
# The input separates workflows from parts 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 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 sorter = parse(buffer.to-text(input)) try
print(part-one(sorter))
print(part-two(sorter))
Day 20Pulse Propagation
The input describes a network of modules: a broadcaster that forwards each pulse to all of its outputs, flip-flops that flip only on low pulses, and conjunctions that remember the latest pulse from each input and answer low only when every remembered pulse is high. Pressing the button sends one low pulse into the broadcaster, and all pulses finish processing before the next press. Part one asks for the product of the total low and high pulse counts after 1000 presses. Part two asks for the fewest presses needed before the module named rx receives a single low pulse.
Show solution
Output
32000000 0
# Advent of Code 2023, day 20 — Pulse Propagation (solution words).
# The network simulates with FIFO queues of pulses and no recursion:
# one press enqueues the button's low pulse, then drains the queue in
# send order — broadcaster repeats, flip-flops toggle on low and send
# their new state, conjunctions remember each input's latest pulse and
# answer low only when every remembered pulse is high. Part 1 counts
# pulses over 1000 presses. Part 2 needs the first press at which rx
# receives a low pulse: the input's shape feeds rx from one conjunction
# whose inputs each pulse high on their own cycle, so the answer is the
# least common multiple of the first press each input sends that parent
# a high pulse (Euclid's gcd, hand-rolled — the language ships no gcd).
## The network as parallel lists: names, kinds (0 broadcaster, 1
## flip-flop, 2 conjunction, 3 untyped output), target lists, and
## conjunction input lists, plus the mutable state — flip-flop on/off
## and each conjunction's memory of its inputs.
type Network = record
names: List<String>
kinds: List<Int>
targets: List<List<String>>
inputs: List<List<String>>
ff-on: Map<String, Bool>
mem: Map<String, Bool>
word _is(a: String, b: String) -> Bool
a == b
# A name's module index, -1 when absent.
word _index-of(names: List<String>, name: String) -> Int
var found = -1
var at = 0
while found == -1 and at < list.length(names)
if _is(names[at], name)
found = at
at = at + 1
found
# A bool map's value, false when unset.
word _flag(flags: Map<String, Bool>, key: String) -> Bool
match flags[key]
case Option.Some(value)
value
case Option.None
false
## Parse the module lines; undeclared targets become untyped outputs,
## and every conjunction's inputs and memory start remembered-low.
word parse(text: String) -> Network
let names: List<String> = []
let kinds: List<Int> = []
let targets: List<List<String>> = []
for line in text.split(text, "\n")
if text.length(line) > 0
let sides = text.split(line, " -> ")
if text.starts-with(line, "%")
list.append(names, text.slice(line, 1, text.index-of(line, " ")))
list.append(kinds, 1)
elif text.starts-with(line, "&")
list.append(names, text.slice(line, 1, text.index-of(line, " ")))
list.append(kinds, 2)
else
list.append(names, sides[0])
list.append(kinds, 0)
let outs: List<String> = []
for target in text.split(sides[1], ", ")
list.append(outs, target)
let added = list.append(targets, outs)
# targets named by nobody: untyped output modules
var settled = false
while not settled
settled = true
var at = 0
while at < list.length(names)
var t = 0
while t < list.length(targets[at])
if _index-of(names, targets[at][t]) == -1
list.append(names, targets[at][t])
list.append(kinds, 3)
list.append(targets, [])
settled = false
t = t + 1
at = at + 1
# conjunction inputs: everyone targeting them
let inputs: List<List<String>> = []
let ff-on: Map<String, Bool> = {}
let mem: Map<String, Bool> = {}
for at in range(0, list.length(names))
let ins: List<String> = []
if kinds[at] == 2
for other in range(0, list.length(names))
if list.any(targets[other], _is(_, names[at]))
let added = list.append(ins, names[other])
for input in ins
mem[names[at] + "|" + input] = false
if kinds[at] == 1
ff-on[names[at]] = false
list.append(inputs, ins)
Network(names, kinds, targets, inputs, ff-on, mem)
# Queue one pulse onto the parallel queue lists.
word _send(q-from: List<String>, q-to: List<String>, q-high: List<Bool>, from: String, to: String, high: Bool)
list.append(q-from, from)
list.append(q-to, to)
list.append(q-high, high)
# Simulate one button press to completion: low and high pulse counts,
# with every high pulse into the watched parent recorded at its press
# number (the parent is "" when nobody is watched).
word _press(net: Network, parent: String, first-high: Map<String, Int>, press-no: Int) -> List<Int>
let q-from: List<String> = []
let q-to: List<String> = []
let q-high: List<Bool> = []
_send(q-from, q-to, q-high, "button", "broadcaster", false)
var low = 1
var high = 0
var head = 0
while head < list.length(q-to)
let from = q-from[head]
let to = q-to[head]
let pulse = q-high[head]
head = head + 1
if to == parent and pulse
if not map.contains(first-high, from)
first-high[from] = press-no
let at = _index-of(net.names, to)
var send = -1
if net.kinds[at] == 0
if pulse
send = 1
else
send = 0
elif net.kinds[at] == 1
if not pulse
net.ff-on[to] = not _flag(net.ff-on, to)
if _flag(net.ff-on, to)
send = 1
else
send = 0
elif net.kinds[at] == 2
net.mem[to + "|" + from] = pulse
var all-high = true
for input in net.inputs[at]
if not _flag(net.mem, to + "|" + input)
all-high = false
if all-high
send = 0
else
send = 1
if send >= 0
for target in net.targets[at]
_send(q-from, q-to, q-high, to, target, send == 1)
if send == 1
high = high + 1
else
low = low + 1
[low, high]
## The product of low and high pulse counts over 1000 presses.
word part-one(net: Network) -> Int
let blank: Map<String, Int> = {}
var low = 0
var high = 0
for press in range(1, 1001)
let counts = _press(net, "", blank, press)
low = low + counts[0]
high = high + counts[1]
low * high
word _gcd(a: Int, b: Int) -> Int
var x = a
var y = b
while y > 0
let older = y
y = x % y
x = older
x
word _lcm(a: Int, b: Int) -> Int
a / _gcd(a, b) * b
## The first press at which rx receives a low pulse: the least common
## multiple of the first press each input of rx's conjunction parent
## sends it a high pulse. Inputs without an rx return 0.
word part-two(net: Network) -> Int
var parent-at = -1
for at in range(0, list.length(net.names))
if list.any(net.targets[at], _is(_, "rx"))
parent-at = at
if parent-at == -1 or net.kinds[parent-at] != 2
0
else
let parent = net.names[parent-at]
let wanted = list.length(net.inputs[parent-at])
let first-high: Map<String, Int> = {}
var press = 0
while map.length(first-high) < wanted
press = press + 1
let counts = _press(net, parent, first-high, press)
var answer = 1
for input, press-no in first-high
answer = _lcm(answer, press-no)
answer
# Advent of Code 2023, day 20 — Pulse Propagation.
# Reads the module list from stdin until end of input, prints both
# answers.
word main()
# shortcut: a module line holds names, %/&/-> 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
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 net = parse(buffer.to-text(input))
print(part-one(net))
print(part-two(net))
Day 21Step Counter
The input maps garden plots, rocks, and a starting tile marked S, and each step moves onto an adjacent plot tile, never onto a rock. Part one asks how many plots the Elf can reach in exactly 64 steps. Part two tiles the same garden infinitely in every direction and asks how many plots are reachable in exactly 26,501,365 steps.
Show solution
Output
16 6536
# Advent of Code 2023, day 21 — Step Counter (solution words). The walk
# is breadth-first from S, and a plot counts for a step total when its
# first distance matches that total's parity — spare steps wiggle in
# place. Part 1 keeps the walk inside the mapped garden; part 2 tiles the
# garden infinitely, where the real question's 26501365 steps ride a
# quadratic: with S centered, 26501365 = 65 + 202300*131, and the counts
# at 65, 65+131, and 65+2*131 steps pin the parabola the far tiles keep
# filling in lockstep, so the answer is Lagrange's k=202300 value.
## The start tile's position.
type Start = record
x: Int
y: Int
## Parse the garden map 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 grid's width.
word _width(grid: List<String>) -> Int
text.length(grid[0])
# The start tile's position.
word _start(grid: List<String>) -> Start
var found-x = 0
var found-y = 0
var found = false
var y = 0
while not found and y < list.length(grid)
let x = text.index-of(grid[y], "S")
if x >= 0
found = true
found-x = x
found-y = y
y = y + 1
Start(found-x, found-y)
word _dx(direction: Int) -> Int
if direction == 1
1
elif direction == 3
-1
else
0
word _dy(direction: Int) -> Int
if direction == 2
1
elif direction == 0
-1
else
0
# The tile at a position on the infinite tiling: floor-modulo into the
# grid, where only rocks block.
word _plot(grid: List<String>, x: Int, y: Int) -> String
let width = _width(grid)
let height = list.length(grid)
let mx = ((x % width) + width) % width
let my = ((y % height) + height) % height
text.slice(grid[my], mx, mx + 1)
# The plots first reached at each parity, walked breadth-first from S;
# wrap tiles the garden infinitely, otherwise the walk stays inside the
# map. A plot answers a step total when its first distance's parity
# matches the total's.
# shortcut: keys span 500 around S either way, so steps must stay under 500
word _count(grid: List<String>, steps: Int, wrap: Bool) -> Int
let width = _width(grid)
let height = list.length(grid)
let start = _start(grid)
var even = 1
var odd = 0
let seen: Map<Int, Bool> = {}
let init = map.put(seen, (start.y + 500) * 1001 + start.x + 500, true)
var current: List<Int> = [(start.y + 500) * 1001 + start.x + 500]
var distance = 0
while distance < steps and list.length(current) > 0
let next: List<Int> = []
for key in current
let x = key % 1001 - 500
let y = key / 1001 - 500
for direction in range(0, 4)
let nx = x + _dx(direction)
let ny = y + _dy(direction)
let blocked = if wrap
_plot(grid, nx, ny) == "#"
else
nx < 0 or nx >= width or ny < 0 or ny >= height or text.slice(grid[ny], nx, nx + 1) == "#"
if not blocked
let nkey = (ny + 500) * 1001 + nx + 500
if not map.contains(seen, nkey)
let stored = map.put(seen, nkey, true)
list.append(next, nkey)
if (distance + 1) % 2 == 0
even = even + 1
else
odd = odd + 1
distance = distance + 1
current = next
if steps % 2 == 0
even
else
odd
## The plots reachable in exactly 64 steps inside the mapped garden.
word part-one(grid: List<String>, steps: Int = 64) -> Int
_count(grid, steps, false)
## The plots reachable in exactly `steps` steps when the garden repeats
## infinitely in every direction.
word count-at(grid: List<String>, steps: Int) -> Int
_count(grid, steps, true)
## Plots reachable in exactly `steps` steps on the infinite tiling. With S
## centered, a total that is the half width plus a whole number of widths
## fits the tile diamond's quadratic: the counts at half, half + width,
## and half + 2 widths pin it, and Lagrange's form evaluates the far
## repeat exactly.
word part-two(grid: List<String>, steps: Int = 26501365) -> Int
let width = _width(grid)
let half = width / 2
# shortcut: the fit branch wants the real input's shape (S centered,
# steps = half + k*width); other totals walk directly and the walk's
# keys bound those steps to 500
if steps > width * 3 and (steps - half) % width == 0
let f0 = count-at(grid, half)
let f1 = count-at(grid, half + width)
let f2 = count-at(grid, half + 2 * width)
let k = (steps - half) / width
f0 * ((k - 1) * (k - 2) / 2) - f1 * (k * (k - 2)) + f2 * (k * (k - 1) / 2)
else
count-at(grid, steps)
# Advent of Code 2023, day 21 — Step Counter.
# Reads the garden map from stdin until end of input, prints both answers.
word main()
# shortcut: a garden row holds plots, rocks, and the S marker, 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))
# the puzzle walks its 11-row example 6 and 100 steps and a real garden
# 64 and 26501365; the door runs the example
let example = list.length(grid) < 64
let steps = if example
6
else
64
let total = if example
100
else
26501365
print(part-one(grid, steps))
print(part-two(grid, total))
Day 22Sand Slabs
The input snapshots falling bricks of sand, each line giving the two end coordinates of one straight brick. Letting time run settles every brick down onto the ground or onto other bricks. Part one asks how many bricks could be removed one at a time with no other brick falling further as a result. Part two asks for the sum, over every brick, of how many other bricks would fall if it disintegrated.
Show solution
Output
5 7
# Advent of Code 2023, day 22 — Sand Slabs (solution words). The snapshot
# settles brick by brick in height order: each falls onto the tallest
# settled top under its footprint, or the ground. A settled brick's
# supporters are the bricks its bottom rests on — part 1 counts bricks
# that are never a sole supporter, and part 2 chains each removal in
# settled height order: a brick falls exactly when it has supporters and
# every one of them has fallen.
## One brick as its normalized lower and upper corners.
type Brick = record
x1: Int
y1: Int
z1: Int
x2: Int
y2: Int
z2: Int
# The smaller of two numbers.
word _min(a: Int, b: Int) -> Int
if a < b
a
else
b
# The larger of two numbers.
word _max(a: Int, b: Int) -> Int
if a > b
a
else
b
# One corner's three coordinates.
word _coords(text: String) -> List<Int>
let numbers: List<Int> = []
for token in text.split(text, ",")
list.append(numbers, text.to-int(token) try)
numbers
## Parse the snapshot into bricks, each pair of ends normalized so the
## first corner is the lower one.
word parse(text: String) -> List<Brick>
let bricks: List<Brick> = []
for line in text.split(text, "\n")
if text.length(line) > 0
let ends = text.split(line, "~")
let a = _coords(ends[0]) try
let b = _coords(ends[1]) try
let added = list.append(bricks, Brick(_min(a[0], b[0]), _min(a[1], b[1]), _min(a[2], b[2]), _max(a[0], b[0]), _max(a[1], b[1]), _max(a[2], b[2])))
bricks
# The brick's lowest z, the sort key of the settling order.
word _lowest(brick: Brick) -> Int
brick.z1
# Whether two bricks' footprints share an x, y cell.
word _overlaps(a: Brick, b: Brick) -> Bool
not (a.x2 < b.x1 or b.x2 < a.x1 or a.y2 < b.y1 or b.y2 < a.y1)
# The z the brick's bottom lands on: one above the tallest settled top in
# its footprint, or the ground.
word _rest-z(settled: List<Brick>, brick: Brick) -> Int
var top = 0
for other in settled
if _overlaps(other, brick) and other.z2 > top
top = other.z2
top + 1
# Every brick let down onto the ground or the bricks below it, in settled
# height order.
word _settled(bricks: List<Brick>) -> List<Brick>
let falling = list.sort-by(bricks, _lowest(_))
let dropped: List<Brick> = []
for brick in falling
let rest = _rest-z(dropped, brick)
let fall = brick.z1 - rest
list.append(dropped, Brick(brick.x1, brick.y1, brick.z1 - fall, brick.x2, brick.y2, brick.z2 - fall))
list.sort-by(dropped, _lowest(_))
# Each settled brick's supporting bricks, by settled position.
word _supporters(settled: List<Brick>) -> List<List<Int>>
let supporters: List<List<Int>> = []
for i in range(0, list.length(settled))
list.append(supporters, [])
for j in range(0, list.length(settled))
let upon = settled[j]
for i in range(0, list.length(settled))
let below = settled[i]
if i != j and below.z2 + 1 == upon.z1 and _overlaps(below, upon)
let added = list.append(supporters[j], i)
supporters
## How many bricks could disintegrate with nothing else falling: every
## brick except a sole supporter of another.
word part-one(bricks: List<Brick>) -> Int
let settled = _settled(bricks)
let supporters = _supporters(settled)
let sole-supported: List<Int> = []
for i in range(0, list.length(settled))
list.append(sole-supported, 0)
for j in range(0, list.length(settled))
if list.length(supporters[j]) == 1
sole-supported[supporters[j][0]] = 1
var safe = 0
for i in range(0, list.length(settled))
if sole-supported[i] == 0
safe = safe + 1
safe
# Whether every supporter has fallen.
word _all-fallen(supporters: List<Int>, fallen: List<Int>) -> Bool
var all = true
for s in supporters
if fallen[s] == 0
all = false
all
## The sum over every brick of how many others fall when it
## disintegrates.
word part-two(bricks: List<Brick>) -> Int
let settled = _settled(bricks)
let supporters = _supporters(settled)
let n = list.length(settled)
var total = 0
for i in range(0, n)
let fallen: List<Int> = []
for j in range(0, n)
list.append(fallen, 0)
fallen[i] = 1
var count = 0
for j in range(0, n)
if j != i and fallen[j] == 0 and list.length(supporters[j]) > 0 and _all-fallen(supporters[j], fallen)
fallen[j] = 1
count = count + 1
total = total + count
total
# Advent of Code 2023, day 22 — Sand Slabs.
# Reads the brick snapshot from stdin until end of input, prints both answers.
word main()
# shortcut: a snapshot line holds digits, commas, and tildes, 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 bricks = parse(buffer.to-text(input)) try
print(part-one(bricks))
print(part-two(bricks))
Day 23A Long Walk
The input maps hiking trails: open path, forest, and slope arrows that force the next step to go the way the arrow points. A hike runs from the one open tile on the top row to the one on the bottom row without stepping on the same tile twice. Part one asks for the step count of the longest such hike. Part two lets the hike climb slopes as if they were plain path and asks for the same longest hike.
Show solution
Output
94 154
# Advent of Code 2023, day 23 — A Long Walk (solution words). Both parts
# walk longest paths over a junction-compressed trail map: the nodes are
# the two endpoints plus every open cell with three or more open
# neighbors, each edge is the corridor walk between them (following a
# slope's forced direction in part 1, ignoring it in part 2), and a
# depth-first search over the small node graph tries every simple path
# and keeps the longest.
## Parse the trail map 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
word _dx(direction: Int) -> Int
if direction == 1
1
elif direction == 3
-1
else
0
word _dy(direction: Int) -> Int
if direction == 2
1
elif direction == 0
-1
else
0
# The walk's positions, packed one per cell.
word _key(x: Int, y: Int) -> Int
y * 1000 + x
# Whether a cell is on the map and not forest.
word _open(grid: List<String>, x: Int, y: Int) -> Bool
y >= 0 and y < list.length(grid) and x >= 0 and x < text.length(grid[y]) and text.slice(grid[y], x, x + 1) != "#"
# The direction a slope tile forces, or -1 for plain path.
word _slope-dir(tile: String) -> Int
if tile == "^"
0
elif tile == ">"
1
elif tile == "v"
2
elif tile == "<"
3
else
-1
# The nodes: the top and bottom endpoints plus every junction, scanned
# top left to bottom right so the walk runs node 0 to node last.
word _nodes(grid: List<String>) -> List<Int>
let nodes: List<Int> = []
for y in range(0, list.length(grid))
for x in range(0, text.length(grid[y]))
if _open(grid, x, y)
var open-neighbors = 0
for direction in range(0, 4)
if _open(grid, x + _dx(direction), y + _dy(direction))
open-neighbors = open-neighbors + 1
if y == 0 or y == list.length(grid) - 1 or open-neighbors >= 3
let added = list.append(nodes, _key(x, y))
nodes
# A node key's position in the node list.
word _index-of(nodes: List<Int>, key: Int) -> Int
var found = -1
var i = 0
while found < 0 and i < list.length(nodes)
if nodes[i] == key
found = i
i = i + 1
found
## One corridor walk: the node a step in some direction from a node
## reaches, and how many steps it took; the node is -1 when a wall blocks
## the first step.
type Walk = record
node: Int
len: Int
# The direction a corridor cell's walk continues: its one open neighbor
# besides the cell the walk came from.
word _corridor-dir(grid: List<String>, x: Int, y: Int, px: Int, py: Int) -> Int
var chosen = -1
for direction in range(0, 4)
let nx = x + _dx(direction)
let ny = y + _dy(direction)
if _open(grid, nx, ny) and not (nx == px and ny == py)
chosen = direction
chosen
# Walk one edge from a node in a direction, stopping at the first node
# reached; slopes force the way when honored.
word _walk(grid: List<String>, node-at: Map<Int, Bool>, x0: Int, y0: Int, direction: Int, slopes: Bool) -> Walk
let x = x0 + _dx(direction)
let y = y0 + _dy(direction)
if not _open(grid, x, y)
Walk(-1, 0)
else
var cx = x
var cy = y
var px = x0
var py = y0
var steps = 1
var done = false
while not done
if map.contains(node-at, _key(cx, cy))
done = true
else
var nd = -1
if slopes
let forced = _slope-dir(text.slice(grid[cy], cx, cx + 1))
if forced >= 0
nd = forced
if nd < 0
nd = _corridor-dir(grid, cx, cy, px, py)
px = cx
py = cy
cx = cx + _dx(nd)
cy = cy + _dy(nd)
steps = steps + 1
Walk(_key(cx, cy), steps)
## The junction graph: nodes and, per node, the flat pairs of reachable
## neighbor node and corridor length.
type Graph = record
nodes: List<Int>
adj: List<List<Int>>
# The junction graph over the map, slopes honored or climbed.
word _graph(grid: List<String>, slopes: Bool) -> Graph
let nodes = _nodes(grid)
let node-at: Map<Int, Bool> = {}
for key in nodes
let stored = map.put(node-at, key, true)
let adj: List<List<Int>> = []
for key in nodes
list.append(adj, [])
for i in range(0, list.length(nodes))
let x = nodes[i] % 1000
let y = nodes[i] / 1000
for direction in range(0, 4)
let w = _walk(grid, node-at, x, y, direction, slopes)
if w.node >= 0
list.append(adj[i], _index-of(nodes, w.node))
let added = list.append(adj[i], w.len)
Graph(nodes, adj)
# The longest walk left from a node, never revisiting a node.
word _best(adj: List<List<Int>>, flags: List<Int>, node: Int, end: Int, dist: Int) -> Int
if node == end
dist
else
var best = 0
var e = 0
while e < list.length(adj[node])
let row = adj[node]
let to = row[e]
let len = row[e + 1]
if flags[to] == 0
flags[to] = 1
let reached = _best(adj, flags, to, end, dist + len)
flags[to] = 0
if reached > best
best = reached
e = e + 2
best
# The longest hike over the junction graph, endpoint to endpoint.
word _longest(graph: Graph) -> Int
let flags: List<Int> = []
for key in graph.nodes
list.append(flags, 0)
flags[0] = 1
_best(graph.adj, flags, 0, list.length(graph.nodes) - 1, 0)
## The step count of the longest hike that never disobeys a slope.
word part-one(grid: List<String>) -> Int
let graph = _graph(grid, true)
_longest(graph)
## The step count of the longest hike when slopes count as plain path.
word part-two(grid: List<String>) -> Int
let graph = _graph(grid, false)
_longest(graph)
# Advent of Code 2023, day 23 — A Long Walk.
# Reads the trail map from stdin until end of input, prints both answers.
word main()
# shortcut: a trail row holds path, forest, and slope arrows, 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 24Never Tell Me The Odds
The input lists hailstones, each with a position in the air and a constant velocity. Watching only the X and Y axes, two hailstones' straight paths can cross in the future, have crossed in the past, or never cross. Part one asks how many pairs of paths cross in the future inside a large rectangular test area given in the puzzle text. Part two asks for a rock thrown from an integer position at an integer velocity that strikes every hailstone at some future nanosecond, and wants the sum of its starting coordinates.
Show solution
Output
2 47
# Advent of Code 2023, day 24 — Never Tell Me The Odds (solution words).
# The language has no floats, so both parts stay exact in 64-bit
# integers. Part 1 intersects each pair's xy paths as rationals kept in
# numerator/denominator form: future-ness is a sign check, and the test
# area compares the integer part directly and cross-multiplies only the
# bounded remainder, so no product ever leaves the 64-bit range. Part 2
# searches the rock's small velocity: the first two hailstones' xy lines
# pin the rock's x and y exactly, every further hailstone must cross
# that point (one product escaping 64 bits goes through _big-zero's
# 32-bit limbs), and the z velocity then falls out of the collision
# times.
## One hailstone: where it is now and where it is heading.
type Stone = record
px: Int
py: Int
pz: Int
vx: Int
vy: Int
vz: Int
## Parse the hailstone list.
word parse(text: String) -> List<Stone>
let stones: List<Stone> = []
for line in text.split(text, "\n")
if text.length(line) > 0
let numbers: List<Int> = []
for token in text.split(text.replace(line, "@", ","), ",")
list.append(numbers, text.to-int(text.trim(token)) try)
let added = list.append(stones, Stone(numbers[0], numbers[1], numbers[2], numbers[3], numbers[4], numbers[5]))
stones
# Whether p + v * (tn / td) lands in [lo, hi], with td positive, in exact
# arithmetic: a huge quotient puts the crossing far outside, the integer
# part compares directly, and only the bounded remainder cross-multiplies.
# shortcut: exact for the puzzle's ranges (positions to ~4e14, speeds to
# ~1000); a speed past ~9000 would overflow the integer part
word _axis-in(p: Int, v: Int, tn: Int, td: Int, lo: Int, hi: Int) -> Bool
if v == 0
p >= lo and p <= hi
else
let q = tn / td
if q > 1000000000000000
false
else
let base = p + v * q
let f = v * (tn % td)
let av = if v < 0
-v
else
v
let below = base - lo <= -av or (base - lo < av and (base - lo) * td + f < 0)
let above = base - hi >= av or (base - hi > -av and (base - hi) * td + f > 0)
not below and not above
# Whether two hailstones' xy paths cross at a future moment inside the
# test area; parallel paths never cross.
word _crosses(a: Stone, b: Stone, lo: Int, hi: Int) -> Bool
let dx = b.px - a.px
let dy = b.py - a.py
let den = a.vx * b.vy - a.vy * b.vx
if den == 0
false
else
var td = den
var tn = dx * b.vy - dy * b.vx
var sn = dx * a.vy - dy * a.vx
if td < 0
td = -td
tn = -tn
sn = -sn
if tn <= 0 or sn <= 0
false
else
_axis-in(a.px, a.vx, tn, td, lo, hi) and _axis-in(a.py, a.vy, tn, td, lo, hi)
## How many pairs of hailstones cross inside the test area in the future.
word part-one(stones: List<Stone>, lo: Int = 200000000000000, hi: Int = 400000000000000) -> Int
var count = 0
var i = 0
while i < list.length(stones)
var j = i + 1
while j < list.length(stones)
if _crosses(stones[i], stones[j], lo, hi)
count = count + 1
j = j + 1
i = i + 1
count
# Whether a * b + c is zero for products past 64 bits, on 32-bit limbs:
# |a| below 2^63, |b| below 2^24, |c| below 2^45.
word _big-zero(a: Int, b: Int, c: Int) -> Bool
if a == 0
c == 0
else
let neg = a < 0
var mag = if neg
-a
else
a
let lo = mag % 4294967296
let hi = mag / 4294967296
let p-lo = lo * b
let p-hi = hi * b
if p-hi >= 16384
false
else
let m = p-hi * 4294967296 + p-lo
if neg
c == m
else
c == -m
# Whether every hailstone from the third on crosses the xy point the
# first two pin with this velocity: (X - Pi) x di = 0, the long product
# through _big-zero.
word _hits-all(stones: List<Stone>, cx: Int, cy: Int, q: Int, r: Int, d: Int) -> Bool
let s0 = stones[0]
let a0 = s0.vx - cx
let b0 = s0.vy - cy
var ok = true
var i = 2
while ok and i < list.length(stones)
let si = stones[i]
let ai = si.vx - cx
let bi = si.vy - cy
let mx = s0.px - si.px + a0 * q
let my = s0.py - si.py + b0 * q
let l1 = mx * bi - my * ai
let l2 = a0 * r * bi - b0 * r * ai
if not _big-zero(l1, d, l2)
ok = false
i = i + 1
ok
## The rock the search found: its x, y velocity, its x, y start, and
## whether the search held one at all.
type Rock = record
vx: Int
vy: Int
x: Int
y: Int
found: Bool
# The rock's x, y velocity and start, found by searching the small
# velocity space: hailstones 0 and 1's xy lines must meet on every other
# hailstone's line at an integer point, in the future.
# shortcut: the collision time and coordinates are bounded (5e11 and
# ~2e15), the puzzle's ranges; a pathological input could exceed them
word _rock-xy(stones: List<Stone>, vmax: Int) -> Rock
let s0 = stones[0]
let s1 = stones[1]
var cx = 0 - vmax
var rvx = 0
var rvy = 0
var rx = 0
var ry = 0
var found = false
while not found and cx <= vmax
var cy = 0 - vmax
while not found and cy <= vmax
let a0 = s0.vx - cx
let b0 = s0.vy - cy
let a1 = s1.vx - cx
let b1 = s1.vy - cy
let den = a0 * b1 - b0 * a1
if den != 0
var num = (s1.px - s0.px) * b1 - (s1.py - s0.py) * a1
var d = den
if d < 0
d = -d
num = -num
if num > 0 and num <= 500000000000 * d
let q = num / d
let r = num % d
if _hits-all(stones, cx, cy, q, r, d)
if (a0 * r) % d == 0 and (b0 * r) % d == 0
found = true
rvx = cx
rvy = cy
rx = s0.px + a0 * q + (a0 * r) / d
ry = s0.py + b0 * q + (b0 * r) / d
cy = cy + 1
cx = cx + 1
Rock(rvx, rvy, rx, ry, found)
# The rock's z at a candidate z velocity: hailstone 0's collision time
# fixes it, hailstone 1 must land the same z.
word _rock-z-at(stones: List<Stone>, rock: Rock, cz: Int) -> Option<Int>
let s0 = stones[0]
let s1 = stones[1]
var n0 = rock.x - s0.px
var d0 = s0.vx - rock.vx
if d0 == 0
n0 = rock.y - s0.py
d0 = s0.vy - rock.vy
let n1 = rock.x - s1.px
let d1 = s1.vx - rock.vx
if d0 == 0 or d1 == 0
Option.None
elif (n0 < 0) != (d0 < 0) and n0 != 0
Option.None
elif (n1 < 0) != (d1 < 0) and n1 != 0
Option.None
else
let num = n0 * (s0.vz - cz)
let num1 = n1 * (s1.vz - cz)
if num % d0 != 0 or num1 % d1 != 0
Option.None
else
let pz = s0.pz + num / d0
if s1.pz + num1 / d1 == pz
Option.Some(pz)
else
Option.None
## The sum of the rock's starting coordinates. The marker 0 - 1 answers
## an input no search bound held; every real puzzle input finds its rock.
word part-two(stones: List<Stone>, vmax: Int = 1000) -> Int
let rock = _rock-xy(stones, vmax)
if not rock.found
0 - 1
else
var cz = 0 - vmax
var answer = 0
var done = false
while not done and cz <= vmax
let spot = _rock-z-at(stones, rock, cz)
match spot
case Option.Some(pz)
done = true
answer = rock.x + rock.y + pz
case Option.None
cz = cz + 1
if done
answer
else
0 - 1
# Advent of Code 2023, day 24 — Never Tell Me The Odds.
# Reads hailstones from stdin until end of input, prints both answers.
word main()
# shortcut: a hailstone line holds digits, commas, an @, and spacing, 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 stones = parse(buffer.to-text(input)) try
# the puzzle checks its five-stone example inside 7..27 with a slow rock
# and the real list inside 2e14..4e14; the door runs the example
let example = list.length(stones) < 10
let lo = if example
7
else
200000000000000
let hi = if example
27
else
400000000000000
let vmax = if example
10
else
1000
print(part-one(stones, lo, hi))
print(part-two(stones, vmax))
Day 25Snowverload
The input is a wiring diagram listing, for each component, the components it connects to. Unplugging the right three wires splits the components into two separate groups. Part one asks for the product of the two groups' sizes. Part two is the year's finale: with every star collected it asks nothing further, and the customary completion answer is the star itself.
Show solution
Output
54 *
# Advent of Code 2023, day 25 — Snowverload (solution words). The three
# wires to unplug are a minimum cut of size three, found by max flow:
# push up to four edge-disjoint paths from the first component to each
# other one; the first terminal that stops at three flows sits across
# the cut, and the wires left dry by the blocked search split the
# components into the two groups. Wires are undirected, so each
# direction carries capacity one and opposite flows cancel.
## The wiring diagram: components by number, each one's incident wire
## numbers, and each wire's far end (wire k pairs with k + 1 when k is
## even, k - 1 when odd).
type Wiring = record
count: Int
adj: List<List<Int>>
far: List<Int>
# A component's number, or -1 while the diagram has not named it.
word _id-of(ids: Map<String, Int>, name: String) -> Int
match ids[name]
case Option.Some(id)
id
case Option.None
0 - 1
# A component's number, naming it on first sight.
word _name(ids: Map<String, Int>, name: String, count: Int) -> Int
let known = _id-of(ids, name)
if known >= 0
known
else
let stored = map.put(ids, name, count)
count
## Parse the wiring diagram; every wire appears exactly once.
word parse(text: String) -> Wiring
let ids: Map<String, Int> = {}
var count = 0
let adj: List<List<Int>> = []
let far: List<Int> = []
for line in text.split(text, "\n")
if text.length(line) > 0
let parts = text.split(line, ": ")
let from = _name(ids, parts[0], count)
if from == count
count = count + 1
let added = list.append(adj, [])
for name in text.split(text.trim(parts[1]), " ")
let to = _name(ids, name, count)
if to == count
count = count + 1
let added = list.append(adj, [])
list.append(adj[from], list.length(far))
list.append(far, to)
list.append(adj[to], list.length(far))
list.append(far, from)
Wiring(count, adj, far)
# A wire's residual partner.
word _pair(wire: Int) -> Int
if wire % 2 == 0
wire + 1
else
wire - 1
# Whether a breadth-first search over wires with capacity left reaches
# `to` from `from`, recording each component's arriving wire in `came`
# (-1 unvisited, -2 the start).
word _reaches(w: Wiring, caps: List<Int>, from: Int, to: Int, came: List<Int>) -> Bool
var i = 0
while i < w.count
came[i] = 0 - 1
i = i + 1
came[from] = 0 - 2
let queue: List<Int> = [from]
var head = 0
var found = from == to
while not found and head < list.length(queue)
let node = queue[head]
head = head + 1
let wires = w.adj[node]
var wi = 0
while not found and wi < list.length(wires)
let wire = wires[wi]
let next = w.far[wire]
if caps[wire] > 0 and came[next] == 0 - 1
came[next] = wire
if next == to
found = true
else
let added = list.append(queue, next)
wi = wi + 1
found
# How many wires (to a limit of four) carry `from` to `to` at once,
# flipping capacities along each path found.
word _flow(w: Wiring, caps: List<Int>, from: Int, to: Int) -> Int
let came: List<Int> = []
var i = 0
while i < w.count
list.append(came, 0)
i = i + 1
var carried = 0
var more = true
while more and carried < 4
if _reaches(w, caps, from, to, came)
carried = carried + 1
var node = to
while node != from
let wire = came[node]
caps[wire] = caps[wire] - 1
let back = _pair(wire)
caps[back] = caps[back] + 1
node = w.far[back]
else
more = false
carried
## The product of the two groups three unplugged wires leave: the first
## component whose four-path flow stops at three, with the groups read
## off the wires the blocked search left dry.
word part-one(w: Wiring) -> Int
var t = 1
var answer = 0
while t < w.count and answer == 0
let caps: List<Int> = []
var i = 0
while i < list.length(w.far)
list.append(caps, 1)
i = i + 1
if _flow(w, caps, 0, t) == 3
let came: List<Int> = []
var j = 0
while j < w.count
list.append(came, 0)
j = j + 1
# to = count cannot be reached, so the search just marks the
# dry side
let reached = _reaches(w, caps, 0, w.count, came)
var side = 1
var k = 1
while k < w.count
if came[k] >= 0
side = side + 1
k = k + 1
answer = side * (w.count - side)
t = t + 1
answer
# Advent of Code 2023, day 25 — Snowverload.
# Reads the wiring diagram from stdin until end of input, prints the answer.
word main()
# shortcut: a wiring line holds names, a colon, and spaces, 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))
# the finale has one part; the second star comes with the first
print("*")
Day 1Historian Hysteria
The input holds two lists of location IDs, one per column. Pair the smallest number in the left list with the smallest in the right, the second-smallest with the second-smallest, and so on, and measure how far apart each pair is. Part one asks for the total distance across all pairs. Part two measures similarity instead: multiply each left ID by how many times it appears in the right list, and total those products.
Show solution
Output
11 31
# Advent of Code 2024, day 1 — Historian Hysteria (solution words).
# The input holds two columns of location IDs. Part 1 pairs the two sorted
# columns rank by rank and totals the distances; part 2 totals each left
# ID times how often it appears in the right column.
type Lists = record
left: List<Int>
right: List<Int>
## Parse the two columns of space-separated location IDs.
word parse(text: String) -> Lists
let left: List<Int> = []
let right: List<Int> = []
for line in text.split(text, "\n")
if text.length(line) > 0
let gap = text.index-of(line, " ")
list.append(left, text.to-int(text.slice(line, 0, gap)) try)
let added = list.append(right, text.to-int(text.slice(line, gap + 1, text.length(line))) try)
Lists(left, right)
## Total the distances between the two sorted columns, rank by rank.
word part-one(lists: Lists) -> Int
let left = list.sort(lists.left)
let right = list.sort(lists.right)
var total = 0
for index, value in left
let distance = value - right[index]
if distance < 0
total = total - distance
else
total = total + distance
total
word _seen(counts: Map<Int, Int>, value: Int) -> Int
match counts[value]
case Option.Some(count)
count
case Option.None
0
## Total each left ID times its count in the right column.
word part-two(lists: Lists) -> Int
let counts: Map<Int, Int> = {}
for value in lists.right
counts[value] = _seen(counts, value) + 1
var total = 0
for value in lists.left
total = total + value * _seen(counts, value)
total
# Advent of Code 2024, day 1 — Historian Hysteria.
# Reads the location IDs from stdin until end of input, prints both answers.
word main()
# shortcut: an ID line is always two integers around one space, 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 lists = parse(buffer.to-text(input)) try
print(part-one(lists))
print(part-two(lists))
Day 2Red-Nosed Reports
The input lists reports, one per line, each a row of numbers called levels. A report is safe when its levels are all increasing or all decreasing and any two adjacent levels differ by at least one and at most three. Part one asks how many reports are safe. Part two adds a tolerance called the Problem Dampener: a report also counts as safe when removing a single level would make the remaining levels safe.
Show solution
Output
2 4
# Advent of Code 2024, day 2 — Red-Nosed Reports (solution words).
# A report is a row of levels; it is safe when every step moves the same
# way by 1 to 3. Part 1 counts the safe reports; part 2 also accepts a
# report when removing one level makes it safe.
## Parse the space-separated level rows into one list per report.
word parse(text: String) -> List<List<Int>>
let reports: List<List<Int>> = []
for line in text.split(text, "\n")
if text.length(line) > 0
let levels: List<Int> = []
for field in text.split(line, " ")
list.append(levels, text.to-int(field) try)
let added = list.append(reports, levels)
reports
# All steps must share one direction and stay within 1..3 in size.
word _safe(levels: List<Int>) -> Bool
var increasing = true
var decreasing = true
var bounded = true
for index in range(1, list.length(levels))
let step = levels[index] - levels[index - 1]
if step <= 0
increasing = false
if step >= 0
decreasing = false
if step < -3 or step > 3
bounded = false
(increasing or decreasing) and bounded
## Count the reports that are safe as they arrive.
word part-one(reports: List<List<Int>>) -> Int
var safe-count = 0
for report in reports
if _safe(report)
safe-count = safe-count + 1
safe-count
word _without(levels: List<Int>, skip: Int) -> List<Int>
let rest: List<Int> = []
for index, value in levels
if index != skip
let added = list.append(rest, value)
rest
## Count the reports that are safe, one removable level tolerated.
word part-two(reports: List<List<Int>>) -> Int
var safe-count = 0
for report in reports
if _safe(report)
safe-count = safe-count + 1
else
var tolerated = false
var skip = 0
while not tolerated and skip < list.length(report)
if _safe(_without(report, skip))
tolerated = true
skip = skip + 1
if tolerated
safe-count = safe-count + 1
safe-count
# Advent of Code 2024, day 2 — Red-Nosed Reports.
# Reads the reports from stdin until end of input, prints both answers.
word main()
# shortcut: a report line is always integers around spaces, 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 reports = parse(buffer.to-text(input)) try
print(part-one(reports))
print(part-two(reports))
Day 3Mull It Over
The input is a stretch of corrupted computer memory holding letters, symbols, and a few intact mul(X, Y) instructions, where X and Y are one- to three-digit numbers. Part one asks for the sum of the products of all the intact instructions. Part two honors two more intact instructions, do() and don't(), which switch the multiplying on and off from wherever they appear; only instructions left on are summed.
Show solution
Output
161 161
# Advent of Code 2024, day 3 — Mull It Over (solution words).
# Corrupted memory holds mul(X,Y) instructions; part 1 totals every intact
# product, part 2 only the ones the do()/don't() toggles leave enabled.
# There is no regex, so both parts scan by text.index-of.
type Token = record
kind: String
at: Int
type Step = record
gained: Int
rest: String
enabled: Bool
## Join the input lines into one memory string, as the reference scans do.
word parse(text: String) -> String
flow text
text.split("\n")
text.join("")
text.trim
word _earliest(rest: String, token: String, kind: String, best: Token) -> Token
let at = text.index-of(rest, token)
if at >= 0 and (best.at < 0 or at < best.at)
Token(kind, at)
else
best
# Whether the fragment is one to three plain digits.
word _digits(fragment: String) -> Bool
var ok = text.length(fragment) >= 1
var index = 0
while ok and index < text.length(fragment)
if not text.contains("0123456789", text.slice(fragment, index, index + 1))
ok = false
index = index + 1
ok
# The product of a "digits,digits" fragment, or -1 when it is malformed.
# A valid product is never negative, so -1 is an unambiguous reject.
word _product(inner: String) -> Int
let comma = text.index-of(inner, ",")
if comma < 0
-1
else
let x-part = text.slice(inner, 0, comma)
let y-part = text.slice(inner, comma + 1, text.length(inner))
if _digits(x-part) and _digits(y-part) and text.length(x-part) <= 3 and text.length(y-part) <= 3 and not text.contains(y-part, ",")
let x = text.to-int(x-part) catch 0
let y = text.to-int(y-part) catch 0
x * y
else
-1
# Consume the mul( that starts `after`: a well-formed instruction gains its
# product and skips past its closing paren, a malformed one gains nothing
# and rescans from just past "mul(" so nested instructions still surface.
word _step-mul(after: String, enabled: Bool) -> Step
let close = text.index-of(after, ")")
if close < 0
Step(0, "", enabled)
else
let product = _product(text.slice(after, 0, close))
if product >= 0 and enabled
Step(product, text.slice(after, close + 1, text.length(after)), enabled)
else
if product >= 0
Step(0, text.slice(after, close + 1, text.length(after)), enabled)
else
Step(0, after, enabled)
## Total every intact mul instruction, toggles ignored.
word part-one(text: String) -> Int
var rest = text
var total = 0
while text.length(rest) > 0
let at = text.index-of(rest, "mul(")
if at < 0
rest = ""
else
let step = _step-mul(text.slice(rest, at + 4, text.length(rest)), true)
total = total + step.gained
rest = step.rest
total
## Total only the mul instructions the do()/don't() toggles leave enabled.
word part-two(text: String) -> Int
var rest = text
var total = 0
var enabled = true
while text.length(rest) > 0
var best = Token("none", -1)
best = _earliest(rest, "mul(", "mul", best)
best = _earliest(rest, "do()", "do", best)
best = _earliest(rest, "don't()", "dont", best)
if best.at < 0
rest = ""
else
if best.kind == "do"
enabled = true
rest = text.slice(rest, best.at + 4, text.length(rest))
elif best.kind == "dont"
enabled = false
rest = text.slice(rest, best.at + 7, text.length(rest))
else
let step = _step-mul(text.slice(rest, best.at + 4, text.length(rest)), enabled)
total = total + step.gained
rest = step.rest
total
# Advent of Code 2024, day 3 — Mull It Over.
# Reads the corrupted memory from stdin until end of input, prints both answers.
word main()
# shortcut: this day's sample alphabet never spells the sentinel, so 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 memory = parse(buffer.to-text(input))
print(part-one(memory))
print(part-two(memory))
Day 4Ceres Search
The input is a grid of letters, and the goal is a word search for XMAS. The word may run horizontally, vertically, or diagonally, forwards or backwards, and matches may overlap. Part one asks how many times XMAS appears in the grid. Part two searches for a cross instead: two MAS spellings sharing one A as their center, one running down each diagonal, and asks how many such crosses the grid holds.
Show solution
Output
18 9
# Advent of Code 2024, day 4 — Ceres Search (solution words).
# The grid stays a list of row strings. Part 1 counts XMAS spellings in
# all eight directions from each X; part 2 counts MAS crosses around
# each A center.
type Offset = record
dr: Int
dc: Int
## Parse the non-empty input lines into the 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 _cell(grid: List<String>, row: Int, column: Int) -> String
if row < 0 or row >= list.length(grid) or column < 0 or column >= text.length(grid[row])
""
else
text.slice(grid[row], column, column + 1)
word _offsets() -> List<Offset>
[Offset(0, 1), Offset(0, -1), Offset(1, 0), Offset(-1, 0), Offset(1, 1), Offset(1, -1), Offset(-1, 1), Offset(-1, -1)]
# Whether MAS continues from an X along one offset, bounds included.
word _spells-mas(grid: List<String>, row: Int, column: Int, step: Offset) -> Bool
var spells = true
var index = 1
while spells and index <= 3
let want = text.slice("MAS", index - 1, index)
if _cell(grid, row + step.dr * index, column + step.dc * index) != want
spells = false
index = index + 1
spells
## Count XMAS spellings in all eight directions, overlaps included.
word part-one(grid: List<String>) -> Int
var count = 0
for row, line in grid
for column in range(0, text.length(line))
if _cell(grid, row, column) == "X"
for step in _offsets()
if _spells-mas(grid, row, column, step)
count = count + 1
count
# Whether one diagonal pair holds M and S in either order.
word _is-mas-pair(first: String, second: String) -> Bool
(first == "M" and second == "S") or (first == "S" and second == "M")
## Count X-shaped MAS crosses: an A center whose two diagonals each
## hold M and S on opposite ends.
word part-two(grid: List<String>) -> Int
var count = 0
for row in range(1, list.length(grid) - 1)
for column in range(1, text.length(grid[row]) - 1)
if _cell(grid, row, column) == "A"
if _is-mas-pair(_cell(grid, row - 1, column - 1), _cell(grid, row + 1, column + 1)) and _is-mas-pair(_cell(grid, row - 1, column + 1), _cell(grid, row + 1, column - 1))
count = count + 1
count
# Advent of Code 2024, day 4 — Ceres Search.
# Reads the letter grid from stdin until end of input, prints both answers.
word main()
# shortcut: a grid line is always letters, 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 5Print Queue
The input has two sections: page ordering rules, each naming two page numbers where the first must print before the second, and updates listing the pages to print in order. Rules about pages an update does not include are ignored. Part one asks for the sum of the middle page numbers of the updates already in the correct order. Part two takes the updates that are out of order, puts their pages in an order the rules accept, and asks for the sum of those corrected updates' middle pages.
Show solution
Output
143 123
# Advent of Code 2024, day 5 — Print Queue (solution words).
# Ordering rules (before|after lines) and comma-separated updates make up
# one manual. Part 1 sums the middle pages of already-valid updates; part 2
# sorts each invalid update by the rules and sums its new middle page.
type Rule = record
before: Int
after: Int
type Manual = record
rules: List<Rule>
updates: List<List<Int>>
## Parse the bar-separated rules, then the comma-separated updates.
word parse(text: String) -> Manual
let rules: List<Rule> = []
let updates: List<List<Int>> = []
for line in text.split(text, "\n")
if text.contains(line, "|")
let bar = text.index-of(line, "|")
let before = text.to-int(text.slice(line, 0, bar)) try
let after = text.to-int(text.slice(line, bar + 1, text.length(line))) try
let added = list.append(rules, Rule(before, after))
else
if text.length(line) > 0
let pages: List<Int> = []
for page in text.split(line, ",")
list.append(pages, text.to-int(page) try)
let added = list.append(updates, pages)
Manual(rules, updates)
# Whether a rule demands second print before first.
word _violates(rules: List<Rule>, first: Int, second: Int) -> Bool
var found = false
for rule in rules
if rule.after == first and rule.before == second
found = true
found
# Whether every pair of pages, earlier and later, follows the rules.
word _valid(rules: List<Rule>, update: List<Int>) -> Bool
var ok = true
for index, page in update
for later in range(index + 1, list.length(update))
if _violates(rules, page, update[later])
ok = false
ok
## Sum the middle pages of the updates already in the correct order.
word part-one(manual: Manual) -> Int
var total = 0
for update in manual.updates
if _valid(manual.rules, update)
total = total + update[list.length(update) / 2]
total
# Whether a rule demands first print before second.
word _prints-before(rules: List<Rule>, first: Int, second: Int) -> Bool
var found = false
for rule in rules
if rule.before == first and rule.after == second
found = true
found
# A fresh list with value inserted at position at.
word _insert(values: List<Int>, at: Int, value: Int) -> List<Int>
let grown: List<Int> = []
var index = 0
while index < at
list.append(grown, values[index])
index = index + 1
list.append(grown, value)
while index < list.length(values)
list.append(grown, values[index])
index = index + 1
grown
# Insertion sort by the pairwise rules; unrelated pages keep their order,
# so the sort is stable under the partial rule order.
word _fixed(rules: List<Rule>, update: List<Int>) -> List<Int>
var sorted: List<Int> = []
for page in update
var at = list.length(sorted)
var scanning = true
while scanning and at > 0
if _prints-before(rules, page, sorted[at - 1])
at = at - 1
else
scanning = false
sorted = _insert(sorted, at, page)
sorted
## Sum the middle pages of the invalid updates once sorted by the rules.
word part-two(manual: Manual) -> Int
var total = 0
for update in manual.updates
if not _valid(manual.rules, update)
let fixed = _fixed(manual.rules, update)
total = total + fixed[list.length(fixed) / 2]
total
# Advent of Code 2024, day 5 — Print Queue.
# Reads the rules and updates from stdin until end of input, prints both answers.
word main()
# The input 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 manual = parse(buffer.to-text(input)) try
print(part-one(manual))
print(part-two(manual))
Day 6Guard Gallivant
The input maps a lab, with # marking obstructions and ^ marking the guard's start facing up. The guard steps forward, turning right 90 degrees whenever something is directly in front. Part one asks how many distinct positions the guard visits, start included, before leaving the map. Part two asks how many positions can hold one extra obstruction, never on the guard's starting position, that traps the guard in a loop she never leaves.
Show solution
Output
41 6
# Advent of Code 2024, day 6 — Guard Gallivant (solution words).
# The lab map holds open cells, # obstructions, and one ^ guard start facing
# up. The guard steps forward, turning right 90 degrees whenever something
# stands directly ahead, until she leaves the map. Part 1 counts her distinct
# visited cells. Part 2 counts the single extra obstructions that trap her in
# a loop: only cells her original walk reaches (minus the start) can change
# anything, and a loop is a repeated position-and-direction state.
## Parse the lab map 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
## One finished walk: the cells visited and whether it ended in a loop.
type Walk = record
cells: Map<String, Bool>
looping: Bool
# The row holding the guard's start marker.
word _guard-row(grid: List<String>) -> Int
var found = 0
var index = 0
while found == 0 and index < list.length(grid)
if text.index-of(grid[index], "^") >= 0
found = index + 1
index = index + 1
found - 1
# The column holding the guard's start marker.
word _guard-column(grid: List<String>) -> Int
text.index-of(grid[_guard-row(grid)], "^")
# The row delta of a direction index: 0 up, 1 right, 2 down, 3 left.
word _dr(direction: Int) -> Int
if direction == 0
-1
elif direction == 2
1
else
0
# The column delta of a direction index.
word _dc(direction: Int) -> Int
if direction == 1
1
elif direction == 3
-1
else
0
# The guard's whole walk with an optional extra obstruction at (ob-r, ob-c):
# every visited cell lands in cells as an "r:c" key, every entered state as an
# "r:c:d" key, and a repeated state ends the walk flagged as a loop.
word _walk(grid: List<String>, ob-r: Int, ob-c: Int) -> Walk
let cells: Map<String, Bool> = {}
let states: Map<String, Bool> = {}
var r = _guard-row(grid)
var c = _guard-column(grid)
var direction = 0
var looping = false
var inside = true
while inside and not looping
map.put(cells, "" + r + ":" + c, true)
let state = "" + r + ":" + c + ":" + direction
if map.contains(states, state)
looping = true
else
map.put(states, state, true)
let nr = r + _dr(direction)
let nc = c + _dc(direction)
if nr < 0 or nr >= list.length(grid) or nc < 0 or nc >= text.length(grid[0])
inside = false
elif text.slice(grid[nr], nc, nc + 1) == "#" or (nr == ob-r and nc == ob-c)
direction = (direction + 1) % 4
else
r = nr
c = nc
Walk(cells, looping)
## Count the distinct cells the guard visits before leaving the map.
word part-one(grid: List<String>) -> Int
let walk = _walk(grid, -1, -1)
map.length(walk.cells)
## Count the extra obstructions that trap the guard in a loop: every cell her
## original walk visits is a candidate, except her start.
word part-two(grid: List<String>) -> Int
let original = _walk(grid, -1, -1)
var placements = 0
for r in range(0, list.length(grid))
for c in range(0, text.length(grid[0]))
if map.contains(original.cells, "" + r + ":" + c)
if not (r == _guard-row(grid) and c == _guard-column(grid))
let retry = _walk(grid, r, c)
if retry.looping
placements = placements + 1
placements
# Advent of Code 2024, day 6 — Guard Gallivant.
# Reads the lab map from stdin until end of input, prints both answers.
word main()
# shortcut: a lab row is ., #, 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 7Bridge Repair
Each input line is an equation: a test value before a colon, then a row of numbers. Inserting + or * between the numbers, evaluated left to right with no rearranging, has to produce the test value for the equation to be true. Part one asks for the sum of the test values of the equations that can be made true. Part two adds a third operator, ||, that concatenates its operands' digits, and asks for the sum again over equations true with all three operators.
Show solution
Output
3749 11387
# Advent of Code 2024, day 7 — Bridge Repair (solution words).
# Each line is a calibration equation: a test value, then a row of numbers
# that keep their order. Inserting + or * between the numbers — evaluated
# left to right, no precedence — makes some equations true; part 2 adds a
# third operator || that concatenates the digits of its operands. Both parts
# search the operator placements recursively, one operand per level, so the
# call depth is the operand count.
## One calibration equation: the test value and its operand row.
type Equation = record
test: Int
parts: List<Int>
# The numbers a space-separated section holds.
word _numbers(section: String) -> List<Int>
let numbers: List<Int> = []
for token in text.split(section, " ")
if text.length(token) > 0
let added = list.append(numbers, text.to-int(token) try)
numbers
## Parse the calibration document into its equations.
word parse(text: String) -> List<Equation>
let equations: List<Equation> = []
for line in text.split(text, "\n")
if text.length(line) > 0
let halves = text.split(line, ":")
let added = list.append(equations, Equation(text.to-int(halves[0]) try, _numbers(halves[1]) try))
equations
# The two operands' digits joined into one number; operands are nonnegative,
# so the parse never fails and the catch only keeps the word pure.
word _concat(a: Int, b: Int) -> Int
text.to-int(int.to-string(a) + b) catch 0
# Whether some operator placement reaches the test value, trying +, *, and
# (when asked) || at every gap; the current value rides the recursion.
word _solvable(test: Int, parts: List<Int>, index: Int, current: Int, concat: Bool) -> Bool
if index == list.length(parts)
current == test
else
let next = parts[index]
var found = _solvable(test, parts, index + 1, current + next, concat)
if not found
found = _solvable(test, parts, index + 1, current * next, concat)
if not found and concat
found = _solvable(test, parts, index + 1, _concat(current, next), concat)
found
## Sum the test values of the equations + and * can make true.
word part-one(equations: List<Equation>) -> Int
var total = 0
for equation in equations
if _solvable(equation.test, equation.parts, 1, equation.parts[0], false)
total = total + equation.test
total
## Sum the test values of the equations +, *, and || can make true.
word part-two(equations: List<Equation>) -> Int
var total = 0
for equation in equations
if _solvable(equation.test, equation.parts, 1, equation.parts[0], true)
total = total + equation.test
total
# Advent of Code 2024, day 7 — Bridge Repair.
# Reads the calibration document from stdin until end of input, prints both
# answers.
word main()
# shortcut: an equation line holds digits, colons, and spaces only, 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 equations = parse(buffer.to-text(input)) try
print(part-one(equations))
print(part-two(equations))
Day 8Resonant Collinearity
The input maps antennas on a grid, where every letter and digit is one frequency, and uppercase and lowercase count separately. Each pair of same-frequency antennas creates two antinodes, one on either side, aligned with the pair and twice as far from one antenna as from the other. Part one asks how many unique in-bounds locations hold at least one antinode. Part two turns on resonant harmonics: every in-bounds point on a pair's whole line becomes an antinode, the antennas themselves included, and the count is taken again.
Show solution
Output
14 34
# Advent of Code 2024, day 8 — Resonant Collinearity (solution words).
# The map marks antennas with letters and digits; every character names a
# frequency, case included, and . is empty space. Two same-frequency
# antennas align antinodes: part 1 places two per pair, each antenna mirrored
# past the other (one antenna twice as far from the point as the other);
# part 2 places one at every in-bounds point of the pair's whole line, the
# antennas included. Antinodes collect in a Map of "r:c" keys — the set
# idiom, since the language has no set type.
## Parse the map 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
## One antenna: its frequency and position.
type Antenna = record
frequency: String
row: Int
column: Int
# Every nonempty cell, reading order.
word _antennas(grid: List<String>) -> List<Antenna>
let antennas: List<Antenna> = []
for r in range(0, list.length(grid))
for c in range(0, text.length(grid[0]))
let cell = text.slice(grid[r], c, c + 1)
if cell != "."
let added = list.append(antennas, Antenna(cell, r, c))
antennas
# A position's set key.
word _key(r: Int, c: Int) -> String
"" + r + ":" + c
# Whether a position lies on the map.
word _in-bounds(grid: List<String>, r: Int, c: Int) -> Bool
r >= 0 and r < list.length(grid) and c >= 0 and c < text.length(grid[0])
# Add an in-bounds position to the antinode set.
word _mark(grid: List<String>, nodes: Map<String, Bool>, r: Int, c: Int) -> Unit
if _in-bounds(grid, r, c)
let updated = map.put(nodes, _key(r, c), true)
# The greatest common divisor of two nonnegative numbers.
word _gcd(a: Int, b: Int) -> Int
var x = a
var y = b
while y > 0
let next = y
y = x % y
x = next
x
# The absolute value.
word _abs(value: Int) -> Int
if value < 0
-value
else
value
## Count the unique antinode locations: each same-frequency pair places two,
## one antenna mirrored past the other.
word part-one(grid: List<String>) -> Int
let nodes: Map<String, Bool> = {}
let antennas = _antennas(grid)
for i in range(0, list.length(antennas))
for j in range(i + 1, list.length(antennas))
let a = antennas[i]
let b = antennas[j]
if a.frequency == b.frequency
_mark(grid, nodes, 2 * a.row - b.row, 2 * a.column - b.column)
_mark(grid, nodes, 2 * b.row - a.row, 2 * b.column - a.column)
map.length(nodes)
## Count the unique antinode locations with resonant harmonics: each
## same-frequency pair marks its whole in-bounds line, stepping by the pair's
## primitive direction so points between the antennas count too.
word part-two(grid: List<String>) -> Int
let nodes: Map<String, Bool> = {}
let antennas = _antennas(grid)
for i in range(0, list.length(antennas))
for j in range(i + 1, list.length(antennas))
let a = antennas[i]
let b = antennas[j]
if a.frequency == b.frequency
let dr = b.row - a.row
let dc = b.column - a.column
let g = _gcd(_abs(dr), _abs(dc))
let step-r = dr / g
let step-c = dc / g
var r = a.row
var c = a.column
while _in-bounds(grid, r, c)
_mark(grid, nodes, r, c)
r = r + step-r
c = c + step-c
var back-r = a.row - step-r
var back-c = a.column - step-c
while _in-bounds(grid, back-r, back-c)
_mark(grid, nodes, back-r, back-c)
back-r = back-r - step-r
back-c = back-c - step-c
map.length(nodes)
# Advent of Code 2024, day 8 — Resonant Collinearity.
# Reads the antenna map from stdin until end of input, prints both answers.
word main()
# shortcut: a map row is letters, digits, and dots, 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 9Disk Fragmenter
The input is one line of digits alternating between file lengths and free-space lengths, with files numbered from 0 in order. Compacting moves one block at a time from the end of the disk into the leftmost free space until no gaps remain between file blocks. Part one asks for the checksum of the compacted disk: the sum of each file block's position times its file ID. Part two moves whole files instead: from the highest file ID down, each file slides into the leftmost span of free space that fits it entirely and sits left of it, files never split, and the answer is the checksum of that disk.
Show solution
Output
1928 2858
# Advent of Code 2024, day 9 — Disk Fragmenter (solution words).
# The dense disk map alternates file lengths and free-space lengths, files
# numbered from 0. Part 1 compacts block by block: the last file block
# repeatedly fills the leftmost free block, two pointers walking inward.
# Part 2 moves whole files, highest ID first, each into the leftmost run of
# free blocks wide enough and strictly left of it, never splitting a file;
# a file with no fitting hole stays put. The checksum sums each block's
# position times its file ID over file blocks.
## Parse the dense map into one block list: file IDs, -1 for free space.
word parse(text: String) -> List<Int>
let blocks: List<Int> = []
for line in text.split(text, "\n")
if text.length(line) > 0 and list.length(blocks) == 0
var id = 0
for index in range(0, text.length(line))
let size = text.to-int(text.slice(line, index, index + 1)) try
var count = 0
while count < size
if index % 2 == 0
list.append(blocks, id)
else
list.append(blocks, -1)
count = count + 1
if index % 2 == 0
id = id + 1
blocks
# The sum of each file block's position times its file ID.
word _checksum(blocks: List<Int>) -> Int
var total = 0
for index in range(0, list.length(blocks))
if blocks[index] >= 0
total = total + index * blocks[index]
total
## The checksum after block-by-block compaction: the last file block fills
## the leftmost free block until the pointers meet.
word part-one(disk: List<Int>) -> Int
let blocks: List<Int> = []
for block in disk
list.append(blocks, block)
var free = 0
var tail = list.length(blocks) - 1
var settled = false
while not settled
if free >= tail
settled = true
elif blocks[free] >= 0
free = free + 1
elif blocks[tail] < 0
tail = tail - 1
else
blocks[free] = blocks[tail]
blocks[tail] = -1
_checksum(blocks)
## One file's position on the disk: its start and its length in blocks.
type FileSpan = record
start: Int
size: Int
# Where one file ID's blocks sit; every ID in the disk has a span.
word _file-span(blocks: List<Int>, id: Int) -> FileSpan
var start = -1
var index = 0
while start < 0 and index < list.length(blocks)
if blocks[index] == id
start = index
index = index + 1
var size = 0
while start + size < list.length(blocks) and blocks[start + size] == id
size = size + 1
FileSpan(start, size)
# The start of the first run of free blocks at least size long and entirely
# left of before, -1 when none fits.
word _first-hole(blocks: List<Int>, size: Int, before: Int) -> Int
var found = -1
var run-start = -1
var index = 0
while found < 0 and index < before
if blocks[index] == -1
if run-start < 0
run-start = index
if index + 1 - run-start >= size
found = run-start
else
run-start = -1
index = index + 1
found
## The checksum after whole-file compaction: files move highest ID first,
## each left into the first hole that fits, never split.
word part-two(disk: List<Int>) -> Int
let blocks: List<Int> = []
for block in disk
list.append(blocks, block)
var highest = 0
for block in blocks
if block > highest
highest = block
var id = highest
while id >= 0
let span = _file-span(blocks, id)
let hole = _first-hole(blocks, span.size, span.start)
if hole >= 0
var moved = 0
while moved < span.size
blocks[hole + moved] = id
blocks[span.start + moved] = -1
moved = moved + 1
id = id - 1
_checksum(blocks)
# Advent of Code 2024, day 9 — Disk Fragmenter.
# Reads the dense disk map from stdin until end of input, prints both
# answers.
word main()
# shortcut: the disk map is one line of 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 disk = parse(buffer.to-text(input)) try
print(part-one(disk))
print(part-two(disk))
Day 10Hoof It
The input is a topographic map of heights from 0 to 9. A hiking trail starts at a 0, ends at a 9, and goes up by exactly one at every step, moving only up, down, left, or right; a trailhead's score is the number of 9-height positions its trails can reach. Part one asks for the sum of the scores of all trailheads. Part two rates every trailhead by its number of distinct trails — paths sharing a summit count separately — and asks for the sum of the ratings.
Show solution
Output
36 81
# Advent of Code 2024, day 10 — Hoof It (solution words).
# The topographic map holds heights 0 to 9. A trail climbs from a 0 to a 9,
# up exactly one per step, moving orthogonally. Part 1 scores each trailhead
# by the distinct 9s its trails reach — a breadth-first walk over a Map of
# visited "r:c" keys, the queue an index-walked List. Part 2 rates each
# trailhead by its distinct trails, every path counting separately; a
# recursive count walks the four uphill neighbors, and the strictly climbing
# trail keeps the call depth at ten.
## Parse the topographic map 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 height at one position; every cell is a digit, so the catch only keeps
# the word pure.
word _height(grid: List<String>, r: Int, c: Int) -> Int
text.to-int(text.slice(grid[r], c, c + 1)) catch -1
# Queue an in-bounds neighbor at the wanted height, encoded as
# row * width + column.
word _climb(grid: List<String>, queue: List<Int>, r: Int, c: Int, target: Int) -> Unit
if r >= 0 and r < list.length(grid) and c >= 0 and c < text.length(grid[0])
if _height(grid, r, c) == target
let queued = list.append(queue, r * text.length(grid[0]) + c)
# How many distinct 9-height positions one trailhead's trails reach.
word _score(grid: List<String>, start-r: Int, start-c: Int) -> Int
let visited: Map<String, Bool> = {}
let queue: List<Int> = []
let width = text.length(grid[0])
let first = list.append(queue, start-r * width + start-c)
var index = 0
var nines = 0
while index < list.length(queue)
let pos = queue[index]
let r = pos / width
let c = pos % width
let key = "" + r + ":" + c
if not map.contains(visited, key)
let seen = map.put(visited, key, true)
if _height(grid, r, c) == 9
nines = nines + 1
else
let next = _height(grid, r, c) + 1
_climb(grid, queue, r - 1, c, next)
_climb(grid, queue, r + 1, c, next)
_climb(grid, queue, r, c - 1, next)
_climb(grid, queue, r, c + 1, next)
index = index + 1
nines
## Sum the trailhead scores: the distinct 9s each 0-height position reaches.
word part-one(grid: List<String>) -> Int
var total = 0
for r in range(0, list.length(grid))
for c in range(0, text.length(grid[0]))
if _height(grid, r, c) == 0
total = total + _score(grid, r, c)
total
# How many distinct trails climb from one position to any 9.
word _paths(grid: List<String>, r: Int, c: Int) -> Int
if _height(grid, r, c) == 9
1
else
let next = _height(grid, r, c) + 1
var total = 0
if r > 0 and _height(grid, r - 1, c) == next
total = total + _paths(grid, r - 1, c)
if r < list.length(grid) - 1 and _height(grid, r + 1, c) == next
total = total + _paths(grid, r + 1, c)
if c > 0 and _height(grid, r, c - 1) == next
total = total + _paths(grid, r, c - 1)
if c < text.length(grid[0]) - 1 and _height(grid, r, c + 1) == next
total = total + _paths(grid, r, c + 1)
total
## Sum the trailhead ratings: every distinct trail counts, even ones sharing
## a summit.
word part-two(grid: List<String>) -> Int
var total = 0
for r in range(0, list.length(grid))
for c in range(0, text.length(grid[0]))
if _height(grid, r, c) == 0
total = total + _paths(grid, r, c)
total
# Advent of Code 2024, day 10 — Hoof It.
# Reads the topographic map from stdin until end of input, prints both
# answers.
word main()
# shortcut: a map row is 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 grid = parse(buffer.to-text(input))
print(part-one(grid))
print(part-two(grid))
Day 11Plutonian Pebbles
The input lists the numbers engraved on a line of stones. Every blink changes each stone at once: a 0 becomes 1, a stone with an even number of digits splits into two stones holding the left and right halves, and any other stone is replaced by its number multiplied by 2024. Part one asks how many stones the line holds after 25 blinks. Part two blinks 75 times instead, far past where holding stones one by one could keep up.
Show solution
Output
55312 65601038650482
# Advent of Code 2024, day 11 — Plutonian Pebbles (solution words).
# Every blink rewrites all stones at once: 0 becomes 1, a stone with an
# even number of digits splits into its left and right halves, and any
# other stone grows by a factor of 2024. The line would explode if held
# stone by stone, so both parts count stone values into a map instead:
# each blink maps counts to counts, never materializing the stones.
## Parse the space-separated engraving numbers.
word parse(text: String) -> List<Int>
let stones: List<Int> = []
for line in text.split(text, "\n")
if text.length(line) > 0
for stone in text.split(line, " ")
list.append(stones, text.to-int(stone) try)
stones
word _seen(counts: Map<Int, Int>, stone: Int) -> Int
match counts[stone]
case Option.Some(count)
count
case Option.None
0
# Ten to the power of the exponent, by repeated multiplication.
word _power(exponent: Int) -> Int
var result = 1
for digit in range(0, exponent)
result = result * 10
result
# One blink over the counted stones: rules applied per value, counts added.
word _blink(counts: Map<Int, Int>) -> Map<Int, Int>
let next: Map<Int, Int> = {}
for stone, count in counts
if stone == 0
next[1] = _seen(next, 1) + count
else
let digits = text.length(int.to-string(stone))
if digits % 2 == 0
let split = _power(digits / 2)
let left = stone / split
let right = stone % split
next[left] = _seen(next, left) + count
next[right] = _seen(next, right) + count
else
let grown = stone * 2024
next[grown] = _seen(next, grown) + count
next
# The stone count after the given number of blinks.
word _after(stones: List<Int>, blinks: Int) -> Int
var counts: Map<Int, Int> = {}
for stone in stones
counts[stone] = _seen(counts, stone) + 1
for blink in range(0, blinks)
counts = _blink(counts)
var total = 0
for stone, count in counts
total = total + count
total
## Count the stones after 25 blinks.
word part-one(stones: List<Int>) -> Int
_after(stones, 25)
## Count the stones after 75 blinks.
word part-two(stones: List<Int>) -> Int
_after(stones, 75)
# Advent of Code 2024, day 11 — Plutonian Pebbles.
# Reads the stone engravings from stdin until end of input, prints both answers.
word main()
# shortcut: a stone line is space-separated integers, 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 stones = parse(buffer.to-text(input)) try
print(part-one(stones))
print(part-two(stones))
Day 12Garden Groups
The input maps garden plots by plant letter, and plots of the same letter touching up, down, left, or right form a region. Part one asks for the total price of fencing every region: each region's area times its perimeter, added together. Part two buys fencing in bulk: a region's price becomes its area times its number of straight fence sides, where a straight run counts once however long it is, and the total uses those prices instead.
Show solution
Output
140 80
# Advent of Code 2024, day 12 — Garden Groups (solution words).
# The grid stays a list of row strings; cells are encoded as
# row * width + column when collected. Regions grow by an iterative
# worklist — recursion would meet the 256-call depth limit on wide
# grids. Part 1 prices area times perimeter (perimeter edges are the
# four sides of each plot that do not touch the same region). Part 2
# prices area times sides: a region's sides equal its corners, both
# the outward ones and the inward notches, so corners are counted per
# plot by looking at the three plots around each of its four corners.
## Parse the non-empty input lines into the garden 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
# Whether the plot at the position holds the given plant; out of bounds
# is no, and regions are maximal, so this is the in-region test too.
word _same(grid: List<String>, row: Int, column: Int, plant: String) -> Bool
if row < 0 or row >= list.length(grid) or column < 0 or column >= text.length(grid[row])
false
else
text.slice(grid[row], column, column + 1) == plant
# Whether the encoded cell is already collected.
word _has(cells: List<Int>, id: Int) -> Bool
var found = false
for other in cells
if other == id
found = true
found
# Add the neighbor to the region when it holds the same plant and is
# not collected yet; returns Unit and mutates both lists.
word _reach(grid: List<String>, cells: List<Int>, seen: List<Int>, row: Int, column: Int, plant: String, width: Int)
let id = row * width + column
if _same(grid, row, column, plant) and not _has(seen, id)
list.append(cells, id)
let added = list.append(seen, id)
# Collect one region, worklist style with a cursor instead of a pop.
word _region(grid: List<String>, row: Int, column: Int, seen: List<Int>) -> List<Int>
let width = text.length(grid[0])
let plant = text.slice(grid[row], column, column + 1)
let cells: List<Int> = []
list.append(cells, row * width + column)
list.append(seen, row * width + column)
var at = 0
while at < list.length(cells)
let id = cells[at]
at = at + 1
_reach(grid, cells, seen, id / width - 1, id % width, plant, width)
_reach(grid, cells, seen, id / width + 1, id % width, plant, width)
_reach(grid, cells, seen, id / width, id % width - 1, plant, width)
_reach(grid, cells, seen, id / width, id % width + 1, plant, width)
cells
# The plot's perimeter contribution: sides without a same-plant neighbor.
word _edges(grid: List<String>, row: Int, column: Int) -> Int
let plant = text.slice(grid[row], column, column + 1)
var edges = 0
if not _same(grid, row - 1, column, plant)
edges = edges + 1
if not _same(grid, row + 1, column, plant)
edges = edges + 1
if not _same(grid, row, column - 1, plant)
edges = edges + 1
if not _same(grid, row, column + 1, plant)
edges = edges + 1
edges
## Total every region's area times its perimeter.
word part-one(grid: List<String>) -> Int
let seen: List<Int> = []
let width = text.length(grid[0])
var total = 0
for row, line in grid
for column in range(0, text.length(line))
if not _has(seen, row * width + column)
let cells = _region(grid, row, column, seen)
var perimeter = 0
for id in cells
perimeter = perimeter + _edges(grid, id / width, id % width)
total = total + list.length(cells) * perimeter
total
# One plot's corners: outward where two orthogonal neighbors leave the
# region, inward where both stay and the diagonal neighbor leaves.
word _corners(grid: List<String>, row: Int, column: Int) -> Int
let plant = text.slice(grid[row], column, column + 1)
let north = _same(grid, row - 1, column, plant)
let south = _same(grid, row + 1, column, plant)
let west = _same(grid, row, column - 1, plant)
let east = _same(grid, row, column + 1, plant)
var corners = 0
if not north and not west
corners = corners + 1
if not north and not east
corners = corners + 1
if not south and not west
corners = corners + 1
if not south and not east
corners = corners + 1
if north and west and not _same(grid, row - 1, column - 1, plant)
corners = corners + 1
if north and east and not _same(grid, row - 1, column + 1, plant)
corners = corners + 1
if south and west and not _same(grid, row + 1, column - 1, plant)
corners = corners + 1
if south and east and not _same(grid, row + 1, column + 1, plant)
corners = corners + 1
corners
## Total every region's area times its number of fence sides.
word part-two(grid: List<String>) -> Int
let seen: List<Int> = []
let width = text.length(grid[0])
var total = 0
for row, line in grid
for column in range(0, text.length(line))
if not _has(seen, row * width + column)
let cells = _region(grid, row, column, seen)
var sides = 0
for id in cells
sides = sides + _corners(grid, id / width, id % width)
total = total + list.length(cells) * sides
total
# Advent of Code 2024, day 12 — Garden Groups.
# Reads the garden map from stdin until end of input, prints both answers.
word main()
# shortcut: a garden row is plant letters only, 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 13Claw Contraption
The input describes claw machines: each button A or B moves the claw a fixed distance along two axes, each machine holds one prize, and a prize is won only when the claw lines up with it exactly. A press of A costs 3 tokens and a press of B costs 1, with no button pressed more than 100 times per machine. Part one asks for the fewest total tokens that wins every winnable prize. Part two moves every prize 10000000000000 farther out on both axes and drops the press cap, asking the same fewest total over the machines still solvable in whole presses.
Show solution
Output
480 875318608908
# Advent of Code 2024, day 13 — Claw Contraption (solution words).
# Each machine is a 2x2 integer system: a presses of button A and b of
# button B must land the claw on the prize along both axes. Both parts
# solve it exactly with the determinant — no floats — taking the machine
# only when both press counts come out whole and non-negative. Part 1
# caps presses at 100; part 2 moves each prize 10000000000000 farther
# out and drops the cap.
type Machine = record
ax: Int
ay: Int
bx: Int
by: Int
px: Int
py: Int
# The two value fragments after the colon, like X+94 and Y+34.
word _parts(line: String) -> List<String>
let sides = text.split(line, ": ")
text.split(sides[1], ", ")
# One fragment's number past its two-character X+, Y+, X=, or Y= prefix.
word _value(fragment: String) -> Int
text.to-int(text.slice(fragment, 2, text.length(fragment))) try
## Parse the Button A, Button B, Prize blocks into machines.
word parse(text: String) -> List<Machine>
let machines: List<Machine> = []
for block in text.split(text, "\n\n")
let lines = text.split(block, "\n")
if list.length(lines) == 3
let a = _parts(lines[0])
let b = _parts(lines[1])
let prize = _parts(lines[2])
let added = list.append(machines, Machine(_value(a[0]) try, _value(a[1]) try, _value(b[0]) try, _value(b[1]) try, _value(prize[0]) try, _value(prize[1]) try))
machines
# The exact press counts for both axes, or Option.None when the system
# has no whole-number solution with non-negative counts.
word _presses(machine: Machine) -> Option<List<Int>>
let det = machine.ax * machine.by - machine.ay * machine.bx
if det == 0
Option.None
else
let numA = machine.px * machine.by - machine.py * machine.bx
let numB = machine.ax * machine.py - machine.ay * machine.px
if numA % det != 0 or numB % det != 0
Option.None
else
let a = numA / det
let b = numB / det
if a < 0 or b < 0
Option.None
else
Option.Some([a, b])
# The machine's token cost, or 0 when its prize cannot be won under the
# cap; shortcut: a negative cap means no press limit, part 2's rule.
word _won-cost(machine: Machine, cap: Int) -> Int
match _presses(machine)
case Option.Some(presses)
if cap < 0 or (presses[0] <= cap and presses[1] <= cap)
presses[0] * 3 + presses[1]
else
0
case Option.None
0
## Total tokens to win every prize winnable with at most 100 presses
## per button.
word part-one(machines: List<Machine>) -> Int
var total = 0
for machine in machines
total = total + _won-cost(machine, 100)
total
## Total tokens to win every prize once each sits 10000000000000 farther
## out, with no press cap.
word part-two(machines: List<Machine>) -> Int
var total = 0
for machine in machines
let far = Machine(machine.ax, machine.ay, machine.bx, machine.by, machine.px + 10000000000000, machine.py + 10000000000000)
total = total + _won-cost(far, -1)
total
# Advent of Code 2024, day 13 — Claw Contraption.
# Reads the claw machines from stdin until end of input, prints both answers.
word main()
# The machine blocks are separated by blank lines, so the runner reads to
# end-of-file the same way day 5 does: branching on the end-of-file detail
# (error.detail), which 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 machines = parse(buffer.to-text(input)) try
print(part-one(machines))
print(part-two(machines))
Day 14Restroom Redoubt
The input lists robots in a 101-tile wide, 103-tile tall space, each with a starting position and a velocity in tiles per second, and robots wrap around at the edges without interacting. Part one asks for the safety factor after exactly 100 seconds: the four quadrant robot counts multiplied together, ignoring robots sitting on the middle row or column. Part two watches the robots second by second until they first arrange into a picture of a Christmas tree, and asks how many seconds that takes.
Show solution
Output
12 1
# Advent of Code 2024, day 14 — Restroom Redoubt (solution words).
# Robots wrap around the restroom edges and never interact. Part 1
# multiplies the four quadrant counts after 100 seconds, ignoring the
# middle row and column. Part 2 hunts the frame where the robots spell
# the Easter-egg picture: the first second at which no two robots share
# a tile — the picture frame is the one clumped drawing, and robots
# forming it never overlap. On the twelve-robot worked example that
# first no-overlap second is 1, so the sample value only checks the
# rule, not the picture.
type Robot = record
px: Int
py: Int
vx: Int
vy: Int
## Parse the p=x,y v=x,y robot lines.
word parse(text: String) -> List<Robot>
let robots: List<Robot> = []
for line in text.split(text, "\n")
if text.length(line) > 0
let halves = text.split(line, " ")
let place = text.split(halves[0], "=")
let drift = text.split(halves[1], "=")
let xy = text.split(place[1], ",")
let vxy = text.split(drift[1], ",")
let added = list.append(robots, Robot(text.to-int(xy[0]) try, text.to-int(xy[1]) try, text.to-int(vxy[0]) try, text.to-int(vxy[1]) try))
robots
# shortcut: the worked example's twelve robots live in an 11 by 7 space;
# every other input is the full 101 by 103 restroom
word _width(robots: List<Robot>) -> Int
if list.length(robots) == 12
11
else
101
word _height(robots: List<Robot>) -> Int
if list.length(robots) == 12
7
else
103
# The wrapped remainder, for negative drifts too.
word _mod(value: Int, size: Int) -> Int
let wrapped = value % size + size
wrapped % size
## The safety factor after 100 seconds: the four quadrant counts
## multiplied together, middle row and column excluded.
word part-one(robots: List<Robot>) -> Int
let width = _width(robots)
let height = _height(robots)
var nw = 0
var ne = 0
var sw = 0
var se = 0
for robot in robots
let x = _mod(robot.px + 100 * robot.vx, width)
let y = _mod(robot.py + 100 * robot.vy, height)
if x != width / 2 and y != height / 2
if y < height / 2
if x < width / 2
nw = nw + 1
else
ne = ne + 1
else
if x < width / 2
sw = sw + 1
else
se = se + 1
nw * ne * sw * se
# Whether every robot sits on its own tile at the given second.
word _distinct(robots: List<Robot>, second: Int, width: Int, height: Int) -> Bool
let ids: List<Int> = []
for robot in robots
list.append(ids, _mod(robot.py + second * robot.vy, height) * width + _mod(robot.px + second * robot.vx, width))
let ordered = list.sort(ids)
var clear = true
for index in range(1, list.length(ordered))
if ordered[index - 1] == ordered[index]
clear = false
clear
## The first second at which no two robots share a tile — the Easter-egg
## frame on the full-size input.
word part-two(robots: List<Robot>) -> Int
let width = _width(robots)
let height = _height(robots)
var found = 0
var second = 1
while found == 0
if _distinct(robots, second, width, height)
found = second
else
second = second + 1
found
# Advent of Code 2024, day 14 — Restroom Redoubt.
# Reads the robot list from stdin until end of input, prints both answers.
word main()
# shortcut: a robot line starts with p=, 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 robots = parse(buffer.to-text(input)) try
print(part-one(robots))
print(part-two(robots))
Day 15Warehouse Woes
The input holds a warehouse map — # walls, O boxes, @ the robot — then the robot's sequence of moves. The robot pushes boxes ahead of it, and nothing moves when a box or the robot would hit a wall. Part one asks for the sum of the boxes' GPS coordinates after all moves, where a box's coordinate is 100 times its distance from the top edge plus its distance from the left edge. Part two scales the warehouse to double width, each box becoming a two-tile pair pushed as a whole, and asks for the same sum counted at each box's left half.
Show solution
Output
10092 9021
# Advent of Code 2024, day 15 — Warehouse Woes (solution words).
# The warehouse is a rank-2 Array of single-character tiles, the same
# shape the Game of Life example uses. Part 1 pushes single-tile boxes:
# one chain scan along the move direction shifts a whole run into the
# first gap. Part 2 scales the map to double width — boxes become [ ]
# pairs — and pushes boxes as pairs: horizontal pushes shift the run of
# halves, vertical pushes collect every half that must move by walking
# the pairs ahead of the robot, wall-blocked pushes move nothing.
# A box's GPS coordinate is 100 times its row plus its column, counted
# at the O tile in part 1 and at the [ half in part 2.
type Warehouse = record
grid: Array<String>
rows: Int
cols: Int
moves: List<String>
type Offset = record
dr: Int
dc: Int
## Parse the warehouse map and the move sequence.
word parse(text: String) -> Warehouse
let sections = text.split(text, "\n\n")
let lines: List<String> = []
for line in text.split(sections[0], "\n")
if text.length(line) > 0
let added = list.append(lines, line)
let rows = list.length(lines)
let cols = text.length(lines[0])
let grid: Array<String> = array.new([rows, cols], ".")
for r, line in lines
for c in range(0, text.length(line))
grid[r, c] = text.slice(line, c, c + 1)
let moves: List<String> = []
for line in text.split(sections[1], "\n")
for c in range(0, text.length(line))
list.append(moves, text.slice(line, c, c + 1))
Warehouse(grid, rows, cols, moves)
# The robot's row and column in the grid.
word _robot(grid: Array<String>, rows: Int, cols: Int) -> List<Int>
var rr = 0
var rc = 0
for r in range(0, rows)
for c in range(0, cols)
if grid[r, c] == "@"
rr = r
rc = c
grid[rr, rc] = "."
[rr, rc]
word _delta(move: String) -> Offset
if move == "^"
Offset(-1, 0)
elif move == "v"
Offset(1, 0)
elif move == "<"
Offset(0, -1)
else
Offset(0, 1)
# The sum of 100 * row + column over the tiles holding the mark.
word _gps(grid: Array<String>, rows: Int, cols: Int, mark: String) -> Int
var total = 0
for r in range(0, rows)
for c in range(0, cols)
if grid[r, c] == mark
total = total + (100 * r + c)
total
# One part-one move: walk the box chain to its first gap, shift the run
# into it, and return the robot's new position.
word _step-one(grid: Array<String>, row: Int, column: Int, dr: Int, dc: Int) -> List<Int>
let nr = row + dr
let nc = column + dc
let front = grid[nr, nc]
if front == "#"
[row, column]
else
if front == "."
[nr, nc]
else
var er = nr
var ec = nc
while grid[er, ec] == "O"
er = er + dr
ec = ec + dc
if grid[er, ec] == "#"
[row, column]
else
var ar = er
var ac = ec
while ar != nr or ac != nc
grid[ar, ac] = grid[ar - dr, ac - dc]
ar = ar - dr
ac = ac - dc
grid[nr, nc] = "."
[nr, nc]
## The sum of the boxes' GPS coordinates after all moves.
word part-one(wh: Warehouse) -> Int
let grid: Array<String> = array.new([wh.rows, wh.cols], ".")
for r in range(0, wh.rows)
for c in range(0, wh.cols)
grid[r, c] = wh.grid[r, c]
let at = _robot(grid, wh.rows, wh.cols)
for move in wh.moves
let d = _delta(move)
let next = _step-one(grid, at[0], at[1], d.dr, d.dc)
at[0] = next[0]
at[1] = next[1]
_gps(grid, wh.rows, wh.cols, "O")
# The double-width map: # becomes ##, O becomes [ ], @ becomes @ .
word _scaled(grid: Array<String>, rows: Int, cols: Int) -> Array<String>
let wide: Array<String> = array.new([rows, cols * 2], ".")
for r in range(0, rows)
for c in range(0, cols)
if grid[r, c] == "#"
wide[r, c * 2] = "#"
wide[r, c * 2 + 1] = "#"
else
if grid[r, c] == "O"
wide[r, c * 2] = "["
wide[r, c * 2 + 1] = "]"
else
if grid[r, c] == "@"
wide[r, c * 2] = "@"
wide
# Whether the encoded cell is already collected.
word _has(cells: List<Int>, id: Int) -> Bool
var found = false
for other in cells
if other == id
found = true
found
# The column of the other half of the box half at this position.
word _partner(grid: Array<String>, row: Int, column: Int) -> Int
if grid[row, column] == "["
column + 1
else
column - 1
# Every box half a vertical push must shift, worklist style with a
# cursor, or Option.None when a wall stands ahead of any of them.
word _lifted(grid: Array<String>, cols: Int, row: Int, column: Int, dr: Int) -> Option<List<Int>>
let cells: List<Int> = []
list.append(cells, row * cols + column)
var blocked = false
var at = 0
while at < list.length(cells) and not blocked
let id = cells[at]
at = at + 1
let r = id / cols
let c = id % cols
let pc = _partner(grid, r, c)
if not _has(cells, r * cols + pc)
let added = list.append(cells, r * cols + pc)
if grid[r + dr, c] == "#"
blocked = true
else
if grid[r + dr, c] != "."
if not _has(cells, (r + dr) * cols + c)
let added = list.append(cells, (r + dr) * cols + c)
let bp = _partner(grid, r + dr, c)
if not _has(cells, (r + dr) * cols + bp)
let added = list.append(cells, (r + dr) * cols + bp)
if blocked
Option.None
else
Option.Some(cells)
# Shift the collected box halves one tile along dr, farthest row first.
word _shift(grid: Array<String>, cells: List<Int>, cols: Int, row: Int, dr: Int)
var depth = 0
for id in cells
let d = (id / cols - row) * dr
if d > depth
depth = d
while depth >= 0
for id in cells
if (id / cols - row) * dr == depth
let r = id / cols
let c = id % cols
grid[r + dr, c] = grid[r, c]
grid[r, c] = "."
depth = depth - 1
# One part-two move: wide boxes push as pairs, vertically through the
# collected halves, horizontally through the run of halves.
word _step-two(grid: Array<String>, cols: Int, row: Int, column: Int, dr: Int, dc: Int) -> List<Int>
let nr = row + dr
let nc = column + dc
let front = grid[nr, nc]
if front == "#"
[row, column]
else
if front == "."
[nr, nc]
else
if dr == 0
var ec = nc
while grid[nr, ec] == "[" or grid[nr, ec] == "]"
ec = ec + dc
if grid[nr, ec] == "#"
[row, column]
else
var ac = ec
while ac != nc
grid[nr, ac] = grid[nr, ac - dc]
ac = ac - dc
grid[nr, nc] = "."
[nr, nc]
else
match _lifted(grid, cols, nr, nc, dr)
case Option.Some(cells)
_shift(grid, cells, cols, nr, dr)
[nr, nc]
case Option.None
[row, column]
## The sum of the boxes' GPS coordinates after all moves in the scaled
## warehouse, each box counted at its [ half.
word part-two(wh: Warehouse) -> Int
let grid = _scaled(wh.grid, wh.rows, wh.cols)
let cols = wh.cols * 2
let at = _robot(grid, wh.rows, cols)
for move in wh.moves
let d = _delta(move)
let next = _step-two(grid, cols, at[0], at[1], d.dr, d.dc)
at[0] = next[0]
at[1] = next[1]
_gps(grid, wh.rows, cols, "[")
# Advent of Code 2024, day 15 — Warehouse Woes.
# Reads the warehouse map and moves from stdin until end of input, prints both answers.
word main()
# The map and the moves are separated by a blank line, so the runner
# reads to end-of-file the same way day 5 does: branching on the
# end-of-file detail (error.detail), which 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 warehouse = parse(buffer.to-text(input))
print(part-one(warehouse))
print(part-two(warehouse))
Day 16Reindeer Maze
The input maps a maze with a start marked S and an end marked E. A reindeer starts at S facing east, pays 1 point per step forward and 1000 points per 90-degree turn, and can never enter a wall. Part one asks for the lowest score any route from S to E can earn. Part two asks how many tiles lie on at least one of those best-scoring routes, the start and end tiles included.
Show solution
Output
7036 45
# Advent of Code 2024, day 16 — Reindeer Maze (solution words).
# The maze holds walls, S, and E; the reindeer starts at S facing east,
# pays 1 per forward step and 1000 per 90-degree turn. Both parts run a
# shortest-cost search over position-and-direction states: part 1 reads
# the lowest score at E, part 2 counts the tiles on any best route by
# meeting a forward search from S with a backward search from E.
## Parse the maze 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 a marker, or -1 when absent.
word _row(grid: List<String>, marker: String) -> Int
var found = -1
var index = 0
while found == -1 and index < list.length(grid)
if text.index-of(grid[index], marker) >= 0
found = index
index = index + 1
found
## The column holding a marker on its row, or -1 when absent.
word _column(grid: List<String>, marker: String) -> Int
let row = _row(grid, marker)
if row == -1
-1
else
text.index-of(grid[row], marker)
## The row delta of a direction index: 0 up, 1 east, 2 down, 3 west.
word _dr(direction: Int) -> Int
if direction == 0
-1
elif direction == 2
1
else
0
## The column delta of a direction index.
word _dc(direction: Int) -> Int
if direction == 1
1
elif direction == 3
-1
else
0
## One position-and-direction search state.
type Pos = record
r: Int
c: Int
d: Int
## The map key of a state.
word _key(pos: Pos) -> String
"" + pos.r + ":" + pos.c + ":" + pos.d
## A state's best cost, with 999999999 standing in for unreached.
word _get(dist: Map<String, Int>, key: String) -> Int
match dist[key]
case Option.Some(cost)
cost
case Option.None
999999999
## Best costs from S facing east to every state, by queue relaxation: each
## improved state re-enters the queue, so costs converge like Dijkstra
## without a priority queue.
word _forward(grid: List<String>) -> Map<String, Int>
let dist: Map<String, Int> = {}
let queue: List<Pos> = []
let start = Pos(_row(grid, "S"), _column(grid, "S"), 1)
map.put(dist, _key(start), 0)
list.append(queue, start)
var head = 0
while head < list.length(queue)
let here = queue[head]
head = head + 1
let cost = _get(dist, _key(here))
for nd in [(here.d + 1) % 4, (here.d + 3) % 4]
let turn-key = _key(Pos(here.r, here.c, nd))
if cost + 1000 < _get(dist, turn-key)
map.put(dist, turn-key, cost + 1000)
let added = list.append(queue, Pos(here.r, here.c, nd))
let nr = here.r + _dr(here.d)
let nc = here.c + _dc(here.d)
if nr >= 0 and nr < list.length(grid) and nc >= 0 and nc < text.length(grid[nr]) and text.slice(grid[nr], nc, nc + 1) != "#"
let step-key = _key(Pos(nr, nc, here.d))
if cost + 1 < _get(dist, step-key)
map.put(dist, step-key, cost + 1)
let added = list.append(queue, Pos(nr, nc, here.d))
dist
## Best costs from every state to E, over the reversed moves: a turn stays
## a turn, a forward step is entered from the cell behind, and E in any of
## its four facings costs 0 because arriving is enough.
word _backward(grid: List<String>) -> Map<String, Int>
let dist: Map<String, Int> = {}
let queue: List<Pos> = []
for d in range(0, 4)
let goal = Pos(_row(grid, "E"), _column(grid, "E"), d)
map.put(dist, _key(goal), 0)
list.append(queue, goal)
var head = 0
while head < list.length(queue)
let here = queue[head]
head = head + 1
let cost = _get(dist, _key(here))
for nd in [(here.d + 1) % 4, (here.d + 3) % 4]
let turn-key = _key(Pos(here.r, here.c, nd))
if cost + 1000 < _get(dist, turn-key)
map.put(dist, turn-key, cost + 1000)
let added = list.append(queue, Pos(here.r, here.c, nd))
let pr = here.r - _dr(here.d)
let pc = here.c - _dc(here.d)
if pr >= 0 and pr < list.length(grid) and pc >= 0 and pc < text.length(grid[pr]) and text.slice(grid[pr], pc, pc + 1) != "#"
let step-key = _key(Pos(pr, pc, here.d))
if cost + 1 < _get(dist, step-key)
map.put(dist, step-key, cost + 1)
let added = list.append(queue, Pos(pr, pc, here.d))
dist
## The lowest score any route from S to E can earn.
word part-one(grid: List<String>) -> Int
let dist = _forward(grid)
var best = 999999999
for d in range(0, 4)
let cost = _get(dist, "" + _row(grid, "E") + ":" + _column(grid, "E") + ":" + d)
if cost < best
best = cost
best
## Count the tiles on at least one best route: a tile qualifies when some
## facing's forward and backward costs meet at exactly the best score.
word part-two(grid: List<String>) -> Int
let forward = _forward(grid)
let backward = _backward(grid)
let best = part-one(grid)
var tiles = 0
for r in range(0, list.length(grid))
for c in range(0, text.length(grid[r]))
if text.slice(grid[r], c, c + 1) != "#"
var on-route = false
for d in range(0, 4)
let key = "" + r + ":" + c + ":" + d
if _get(forward, key) + _get(backward, key) == best
on-route = true
if on-route
tiles = tiles + 1
tiles
# Advent of Code 2024, day 16 — Reindeer Maze.
# Reads the maze from stdin until end of input, prints both answers.
word main()
# shortcut: a maze row is map characters, so this sentinel cannot collide;
# it stands in for the end-of-input 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 17Chronospatial Computer
The input gives the starting values of three registers and a program of 3-bit numbers run by a small computer with eight instructions, each reading a literal or combo operand. Part one asks you to run the program and join the values its out instruction produces with commas. Part two resets the registers and asks for the lowest positive starting value of register A that makes the whole program output a copy of itself.
Show solution
Output
5,7,3,0 117440
# Advent of Code 2024, day 17 — Chronospatial Computer (solution words).
# A three-register machine runs a program of opcode-and-operand pairs;
# operand 4, 5, or 6 reads register A, B, or C as a combo operand. Part 1
# runs the parsed registers and joins the out values with commas. Part 2
# searches for the lowest positive A that makes the program output a copy
# of itself: every program digit is one octal digit of A, so the search
# starts at the smallest A with that many digits and nudges the octal
# digit behind the last mismatching output until the copy matches.
## The registers and program from the debugger screen.
type Machine = record
a: Int
b: Int
c: Int
program: List<Int>
## Parse the Register A, B, C lines and the Program line.
word parse(text: String) -> Machine
var a = 0
var b = 0
var c = 0
let program: List<Int> = []
for line in text.split(text, "\n")
if text.length(line) > 0
let parts = text.split(line, ": ")
if parts[0] == "Register A"
let value = text.to-int(parts[1]) catch 0
a = value
elif parts[0] == "Register B"
let value = text.to-int(parts[1]) catch 0
b = value
elif parts[0] == "Register C"
let value = text.to-int(parts[1]) catch 0
c = value
elif parts[0] == "Program"
for token in text.split(parts[1], ",")
let value = text.to-int(token) catch 0
list.append(program, value)
Machine(a, b, c, program)
## Two raised to a power; the machine's divisors stay tiny.
word _pow2(power: Int) -> Int
var value = 1
for _i in range(0, power)
value = value * 2
value
## Eight raised to a power: one more octal digit of A.
word _pow8(power: Int) -> Int
var value = 1
for _i in range(0, power)
value = value * 8
value
## Bitwise xor of two nonnegative integers, one binary digit at a time.
## There is no xor word, and the registers never go negative.
word _xor(left: Int, right: Int) -> Int
var a = left
var b = right
var value = 0
var place = 1
while a > 0 or b > 0
let bit = (a % 2 + b % 2) % 2
if bit == 1
value = value + place
a = a / 2
b = b / 2
place = place * 2
value
## A combo operand's value: 0 to 3 are literals, 4 to 6 read registers.
word _combo(operand: Int, a: Int, b: Int, c: Int) -> Int
if operand <= 3
operand
elif operand == 4
a
elif operand == 5
b
else
c
## Run the program with A starting at a-start, returning the out values.
word _run(machine: Machine, a-start: Int) -> List<Int>
var a = a-start
var b = machine.b
var c = machine.c
var ip = 0
let out: List<Int> = []
while ip < list.length(machine.program)
let opcode = machine.program[ip]
let operand = machine.program[ip + 1]
if opcode == 0
a = a / _pow2(_combo(operand, a, b, c))
ip = ip + 2
elif opcode == 1
b = _xor(b, operand)
ip = ip + 2
elif opcode == 2
b = _combo(operand, a, b, c) % 8
ip = ip + 2
elif opcode == 3
if a != 0
ip = operand
else
ip = ip + 2
elif opcode == 4
b = _xor(b, c)
ip = ip + 2
elif opcode == 5
list.append(out, _combo(operand, a, b, c) % 8)
ip = ip + 2
elif opcode == 6
b = a / _pow2(_combo(operand, a, b, c))
ip = ip + 2
else
c = a / _pow2(_combo(operand, a, b, c))
ip = ip + 2
out
## Run the parsed registers and join the out values with commas.
word part-one(machine: Machine) -> String
let out = _run(machine, machine.a)
var joined = ""
for index, value in out
if index > 0
joined = joined + ","
joined = joined + value
joined
## The lowest positive A that makes the program output a copy of itself.
word part-two(machine: Machine) -> Int
let n = list.length(machine.program)
if n == 0
0
else
var a = _pow8(n - 1)
var found = false
while not found
let out = _run(machine, a)
if list.length(out) > n
# shortcut: no A can shrink an overlong output, so the
# search stops with -1 for programs that never self-output
found = true
a = -1
else
var mismatch = -1
var index = list.length(out) - 1
while mismatch == -1 and index >= 0
if out[index] != machine.program[index]
mismatch = index
index = index - 1
if mismatch == -1 and list.length(out) == n
found = true
else
if mismatch == -1
mismatch = 0
a = a + _pow8(mismatch)
a
# Advent of Code 2024, day 17 — Chronospatial Computer.
# Reads the debugger screen from stdin until end of input, prints both
# answers. The sample is the page's part-two example, whose program can
# output a copy of itself; the part-one example cannot, so part two on it
# would fail loudly instead of looping.
word main()
# shortcut: a debugger line is "Register X: n" or "Program: digits", so
# this sentinel cannot collide; it stands in for the end-of-input 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 machine = parse(buffer.to-text(input))
print(part-one(machine))
print(part-two(machine))
Day 18RAM Run
The input lists grid coordinates, one per line, of bytes falling into a memory space whose coordinates run from 0 to 70 on both axes; each fallen byte corrupts its position, and corrupted positions cannot be entered. Part one asks for the fewest steps from the top-left corner to the bottom-right corner after the first 1024 bytes have fallen. Part two lets the bytes keep falling in order and asks for the coordinates of the first byte whose fall leaves no path to the exit at all.
Show solution
Output
22 6,1
# Advent of Code 2024, day 18 — RAM Run (solution words).
# Bytes fall onto a grid of safe cells, corrupting their coordinates. The
# memory space is 71 by 71 with 1024 fallen bytes on the real input; the
# page's example is 7 by 7 with 12 bytes, and its input is exactly 25
# lines long, which is how the two shapes are told apart here. Part 1
# breadth-first searches the fewest steps from the top left to the bottom
# right after the first bytes fall. Part 2 finds the first byte whose fall
# blocks every path: blocking is monotone — once no path survives, no
# later byte frees one — so a binary search over the fall count lands on
# the exact boundary.
## One falling byte's coordinates.
type Byte = record
x: Int
y: Int
## The grid size, the part-one fall count, and the falling bytes in order.
type Space = record
size: Int
fall: Int
bytes: List<Byte>
## Parse the x,y lines and pick the example or real shape.
word parse(text: String) -> Space
let bytes: List<Byte> = []
for line in text.split(text, "\n")
if text.length(line) > 0
let comma = text.index-of(line, ",")
let x = text.to-int(text.slice(line, 0, comma)) catch 0
let y = text.to-int(text.slice(line, comma + 1, text.length(line))) catch 0
let added = list.append(bytes, Byte(x, y))
if list.length(bytes) == 25
Space(7, 12, bytes)
else
Space(71, 1024, bytes)
## The row delta of a direction index: 0 up, 1 right, 2 down, 3 left.
word _dr(direction: Int) -> Int
if direction == 0
-1
elif direction == 2
1
else
0
## The column delta of a direction index.
word _dc(direction: Int) -> Int
if direction == 1
1
elif direction == 3
-1
else
0
## A position's distance, with -1 standing in for unreached.
word _get(dist: Map<String, Int>, key: String) -> Int
match dist[key]
case Option.Some(steps)
steps
case Option.None
-1
## Fewest steps from (0,0) to the far corner after count bytes have
## fallen, or -1 when no path survives. The queue holds positions packed
## as row times size plus column.
word _bfs(space: Space, count: Int) -> Int
let blocked: Map<String, Bool> = {}
for index in range(0, count)
let byte = space.bytes[index]
map.put(blocked, "" + byte.x + ":" + byte.y, true)
let dist: Map<String, Int> = {}
let queue: List<Int> = []
map.put(dist, "0:0", 0)
list.append(queue, 0)
var head = 0
var steps = -1
while head < list.length(queue) and steps == -1
let pos = queue[head]
head = head + 1
let r = pos / space.size
let c = pos % space.size
let here = _get(dist, "" + r + ":" + c)
if r == space.size - 1 and c == space.size - 1
steps = here
else
for d in range(0, 4)
let nr = r + _dr(d)
let nc = c + _dc(d)
let key = "" + nr + ":" + nc
if nr >= 0 and nr < space.size and nc >= 0 and nc < space.size and not map.contains(blocked, key) and not map.contains(dist, key)
map.put(dist, key, here + 1)
let added = list.append(queue, nr * space.size + nc)
steps
## The fewest steps to the exit after the first fallen bytes.
word part-one(space: Space) -> Int
_bfs(space, space.fall)
## The first byte whose fall blocks every path, as "x,y".
word part-two(space: Space) -> String
var open = space.fall
var blocked = list.length(space.bytes)
while blocked - open > 1
let mid = (open + blocked) / 2
if _bfs(space, mid) == -1
blocked = mid
else
open = mid
let byte = space.bytes[blocked - 1]
"" + byte.x + "," + byte.y
# Advent of Code 2024, day 18 — RAM Run.
# Reads the falling-byte coordinates from stdin until end of input,
# prints both answers.
word main()
# shortcut: a byte line is two numbers around one comma, so this sentinel
# cannot collide; it stands in for the end-of-input 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 space = parse(buffer.to-text(input))
print(part-one(space))
print(part-two(space))
Day 19Linen Layout
The input lists the available towel stripe patterns, then, after a blank line, the designs to display, each a sequence of stripe colors. A design is possible when towels with the available patterns can be laid in order so their stripes match the design exactly. Part one asks how many designs are possible. Part two asks for the total number of distinct ways the available towels can spell every design.
Show solution
Output
6 16
# Advent of Code 2024, day 19 — Linen Layout (solution words).
# The first input line lists the available towel patterns; after a blank
# line, each remaining line is one design. Both parts count what towels
# can spell: ways to cover position i are the sum, over every towel the
# design's remainder starts with, of the ways at that towel's far end,
# filled from the design's end backward in one array. Part 1 counts the
# designs with at least one way; part 2 totals all the ways.
## The available patterns and the desired designs.
type Layout = record
towels: List<String>
designs: List<String>
## Parse the towel line, skip the blank line, collect the designs.
word parse(text: String) -> Layout
let towels: List<String> = []
let designs: List<String> = []
var section = 0
for line in text.split(text, "\n")
if text.length(line) > 0
if section == 0
for towel in text.split(line, ", ")
list.append(towels, towel)
section = 1
else
let added = list.append(designs, line)
Layout(towels, designs)
## The number of ways towels can spell one design exactly. The ways live
## in a rank-1 array filled backward.
word _ways(design: String, towels: List<String>) -> Int
let n = text.length(design)
let counts: Array<Int> = array.new([n + 1], 0)
counts[n] = 1
var i = n - 1
while i >= 0
var total = 0
for towel in towels
let end = i + text.length(towel)
if end <= n and text.starts-with(text.slice(design, i, n), towel)
total = total + counts[end]
counts[i] = total
i = i - 1
counts[0]
## How many designs the available towels can spell.
word part-one(layout: Layout) -> Int
var possible = 0
for design in layout.designs
if _ways(design, layout.towels) > 0
possible = possible + 1
possible
## The total number of distinct towel arrangements over all designs.
word part-two(layout: Layout) -> Int
var total = 0
for design in layout.designs
total = total + _ways(design, layout.towels)
total
# Advent of Code 2024, day 19 — Linen Layout.
# Reads the towel patterns and designs from stdin until end of input,
# prints both answers.
word main()
# shortcut: pattern and design lines hold stripe letters and commas only,
# so this sentinel cannot collide; it stands in for the end-of-input
# 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 layout = parse(buffer.to-text(input))
print(part-one(layout))
print(part-two(layout))
Day 20Race Condition
The input maps a racetrack of walls and track with a single start and end. Once per race a runner may switch off collision for up to two picoseconds, passing through walls as long as it lands back on track. Part one asks how many different cheats save at least 100 picoseconds. Part two widens the cheat to up to twenty picoseconds of wall-passing movement and asks the same count.
Show solution
Output
8 3
# Advent of Code 2024, day 20 — Race Condition (solution words).
# The racetrack holds one simple path from S to E. Both parts walk that
# path once, index every tile by its step, then count cheats: a cheat
# starts and ends on the path, moves at most cheat-length steps by
# Manhattan distance, and saves path steps equal to the index gap minus
# that distance. Part 1 allows 2 steps, part 2 allows 20; the saving
# threshold is a parameter because the page asks for 100 on the real
# racetrack while its examples count 12 and 76.
## One track position.
type Spot = record
r: Int
c: Int
## The walked path and every path tile's step index.
type Track = record
path: List<Spot>
index: Map<String, Int>
## Parse the racetrack into its rows.
word _rows(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 a marker, or -1 when absent.
word _row(grid: List<String>, marker: String) -> Int
var found = -1
var index = 0
while found == -1 and index < list.length(grid)
if text.index-of(grid[index], marker) >= 0
found = index
index = index + 1
found
## The column holding a marker on its row, or -1 when absent.
word _column(grid: List<String>, marker: String) -> Int
let row = _row(grid, marker)
if row == -1
-1
else
text.index-of(grid[row], marker)
## The row delta of a direction index: 0 up, 1 right, 2 down, 3 left.
word _dr(direction: Int) -> Int
if direction == 0
-1
elif direction == 2
1
else
0
## The column delta of a direction index.
word _dc(direction: Int) -> Int
if direction == 1
1
elif direction == 3
-1
else
0
## A path tile's step index, with -1 standing in for off-path.
word _step(index: Map<String, Int>, key: String) -> Int
match index[key]
case Option.Some(step)
step
case Option.None
-1
## Walk the track from S to E: the path is unique, so every step takes the
## one track neighbor that is not the tile just left.
word parse(text: String) -> Track
let grid = _rows(text)
let path: List<Spot> = []
let index: Map<String, Int> = {}
var r = _row(grid, "S")
var c = _column(grid, "S")
let er = _row(grid, "E")
let ec = _column(grid, "E")
var pr = -1
var pc = -1
var walking = true
while walking
map.put(index, "" + r + ":" + c, list.length(path))
list.append(path, Spot(r, c))
if r == er and c == ec
walking = false
else
var moved = false
var d = 0
while not moved and d < 4
let nr = r + _dr(d)
let nc = c + _dc(d)
if nr >= 0 and nr < list.length(grid) and nc >= 0 and nc < text.length(grid[nr]) and text.slice(grid[nr], nc, nc + 1) != "#" and not (nr == pr and nc == pc)
pr = r
pc = c
r = nr
c = nc
moved = true
d = d + 1
Track(path, index)
## Count the cheats that save at least threshold picoseconds while moving
## through at most cheat-length steps: every path tile pairs with the path
## tiles inside that Manhattan box, and a pair saves the index gap minus
## the distance walked.
word _cheats(track: Track, threshold: Int, cheat-length: Int) -> Int
var total = 0
for i in range(0, list.length(track.path))
let here = track.path[i]
for dy in range(-cheat-length, cheat-length + 1)
for dx in range(-cheat-length, cheat-length + 1)
var distance = 0
if dy < 0
distance = distance - dy
else
distance = distance + dy
if dx < 0
distance = distance - dx
else
distance = distance + dx
if distance > 0 and distance <= cheat-length
let j = _step(track.index, "" + (here.r + dy) + ":" + (here.c + dx))
if j > i and j - i - distance >= threshold
total = total + 1
total
## Count 2-step cheats saving at least threshold picoseconds.
word part-one(track: Track, threshold: Int) -> Int
_cheats(track, threshold, 2)
## Count 20-step cheats saving at least threshold picoseconds.
word part-two(track: Track, threshold: Int) -> Int
_cheats(track, threshold, 20)
# Advent of Code 2024, day 20 — Race Condition.
# Reads the racetrack from stdin until end of input, prints both answers.
# The real racetrack counts cheats saving at least 100 picoseconds; the
# page's 15-row example track is far shorter than that, so it keeps the
# page's own example counts instead (12 for 2-step cheats, 76 for 20-step
# cheats), the same sample-versus-real adaptation day 18 makes for its
# grid size.
word main()
# shortcut: a racetrack row is map characters, so this sentinel cannot
# collide; it stands in for the end-of-input 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 track = parse(buffer.to-text(input))
var save-one = 100
var save-two = 100
if list.length(track.path) < 200
save-one = 12
save-two = 76
print(part-one(track, save-one))
print(part-two(track, save-two))
Day 21Keypad Conundrum
The input lists five codes to type on a door's numeric keypad. Your directional keypad moves a robot arm over a second directional keypad, whose presses move another arm over the numeric keypad, and no arm may ever aim at a gap between buttons, even for an instant. Part one asks for the sum of the codes' complexities, each the shortest number of presses you must type multiplied by the code's numeric part. Part two sends the presses through twenty-five robots on directional keypads instead of two, so the shortest sequences grow far past materializing; a table of cheapest button-to-button presses per keypad level carries the count instead.
Show solution
Output
126384 154115708116294
# Advent of Code 2024, day 21 — Keypad Conundrum (solution words).
# Codes are typed on the numeric keypad through a chain of directional
# keypads, every arm starting on A and never allowed to aim at the gap. The
# chain is never materialized: a Map keyed "from>to" holds the cheapest
# press count for one button-to-button transition per directional level, and
# each new level is the best per-pair path typed through the level below.
# The numeric keypad uses the final table the same way. Positions are encoded
# row * 10 + column; the gaps sit at 0 (directional) and 30 (numeric).
## Parse the door codes: one per nonempty line.
word parse(text: String) -> List<String>
let codes: List<String> = []
for line in text.split(text, "\n")
if text.length(line) > 0
let added = list.append(codes, line)
codes
word _abs(n: Int) -> Int
if n < 0
-n
else
n
# Directional keypad buttons: ^ A / < v > with the gap at 0,0.
word _dir-pad() -> Map<String, Int>
let pad: Map<String, Int> = {"^": 1, "A": 2, "<": 10, "v": 11, ">": 12}
pad
# Numeric keypad buttons: 789 / 456 / 123 / _0A with the gap at 3,0.
word _num-pad() -> Map<String, Int>
let pad: Map<String, Int> = {"7": 0, "8": 1, "9": 2, "4": 10, "5": 11, "6": 12, "1": 20, "2": 21, "3": 22, "0": 31, "A": 32}
pad
# Encoded position of a button; every queried button exists, so -1 is dead.
word _key-at(pad: Map<String, Int>, key: String) -> Int
match pad[key]
case Option.Some(position)
position
case Option.None
-1
word _dist(a: Int, b: Int) -> Int
_abs(b / 10 - a / 10) + _abs(b % 10 - a % 10)
# Walk every interleaving of the remaining vertical and horizontal moves,
# dropping any that steps onto the gap; each ordering appears exactly once.
word _walk(pos: Int, vleft: Int, hleft: Int, vdelta: Int, hdelta: Int, vchar: String, hchar: String, prefix: String, gap: Int, out: List<String>) -> Unit
if vleft == 0 and hleft == 0
let added = list.append(out, prefix)
else
if vleft > 0
let next = pos + vdelta
if next != gap
_walk(next, vleft - 1, hleft, vdelta, hdelta, vchar, hchar, prefix + vchar, gap, out)
if hleft > 0
let next = pos + hdelta
if next != gap
_walk(next, vleft, hleft - 1, vdelta, hdelta, vchar, hchar, prefix + hchar, gap, out)
# All minimal gap-avoiding move strings between two buttons of one keypad.
word _paths(pad: Map<String, Int>, gap: Int, from: String, to: String, out: List<String>) -> Unit
let a = _key-at(pad, from)
let b = _key-at(pad, to)
let dr = b / 10 - a / 10
let dc = b % 10 - a % 10
var vdelta = -10
var vchar = "^"
if dr > 0
vdelta = 10
vchar = "v"
var hdelta = -1
var hchar = "<"
if dc > 0
hdelta = 1
hchar = ">"
_walk(a, _abs(dr), _abs(dc), vdelta, hdelta, vchar, hchar, "", gap, out)
# Cost of typing s on one keypad whose arm starts at A: the per-pair table
# summed over consecutive characters.
word _typing-cost(s: String, table: Map<String, Int>) -> Int
var total = 0
var prev = "A"
for index in range(0, text.length(s))
let ch = text.slice(s, index, index + 1)
match table[prev + ch]
case Option.Some(cost)
total = total + cost
case Option.None
total = total
prev = ch
total
# Best press count for every transition of one keypad through the given
# per-pair table, keyed "a>b".
word _best-table(pad: Map<String, Int>, gap: Int, buttons: List<String>, table: Map<String, Int>) -> Map<String, Int>
let best: Map<String, Int> = {}
for a in buttons
for b in buttons
let paths: List<String> = []
_paths(pad, gap, a, b, paths)
var winner = -1
for path in paths
let cost = _typing-cost(path + "A", table)
if winner < 0 or cost < winner
winner = cost
best[a + b] = winner
best
# Sum of code complexities through a chain of `robots` directional keypads.
word _solve(codes: List<String>, robots: Int) -> Int
let pad = _dir-pad()
let buttons: List<String> = ["A", "^", "v", "<", ">"]
var table: Map<String, Int> = {}
for a in buttons
for b in buttons
table[a + b] = _dist(_key-at(pad, a), _key-at(pad, b)) + 1
var level = 2
while level <= robots
table = _best-table(pad, 0, buttons, table)
level = level + 1
let numeric: Map<String, Int> = _best-table(_num-pad(), 30, ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A"], table)
var total = 0
for code in codes
let value = text.to-int(text.slice(code, 0, text.length(code) - 1)) catch 0
total = total + value * _typing-cost(code, numeric)
total
## Sum of complexities with two robots on directional keypads.
word part-one(codes: List<String>) -> Int
_solve(codes, 2)
## Sum of complexities with twenty-five robots on directional keypads.
word part-two(codes: List<String>) -> Int
_solve(codes, 25)
# Advent of Code 2024, day 21 — Keypad Conundrum.
# Reads the door codes from stdin until end of input, prints both answers.
word main()
# shortcut: a code is digits plus A, 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 codes = parse(buffer.to-text(input))
print(part-one(codes))
print(part-two(codes))
Day 22Monkey Market
Each input line is one buyer's initial secret number. A buyer's next secret comes from three steps — multiply by 64, divide by 32 rounding down, multiply by 2048 — each mixed into the secret with a bitwise XOR and pruned to the remainder of dividing by 16777216. Part one asks for the sum of every buyer's 2000th new secret number. Part two watches each buyer's ones-digit prices, banks the price at the first occurrence of every four-change window per buyer, and asks for the window with the largest total.
Show solution
Output
37327623 24
# Advent of Code 2024, day 22 — Monkey Market (solution words).
# Each buyer's secret evolves by three mix-and-prune steps: multiply by 64,
# divide by 32, multiply by 2048, each XOR-ed into the secret and pruned to
# 2^24. Zhex has no bitwise words, so the XOR is a 24-bit bit loop —
# operands are reduced mod 2^24 first, which the prune allows because XOR
# and mod commute on the low bits. Part 2 keys a Map on the string of the
# last four price changes and banks only each buyer's first occurrence of a
# window.
## Parse the initial secrets: one per nonempty line.
word parse(text: String) -> List<Int>
let secrets: List<Int> = []
for line in text.split(text, "\n")
if text.length(line) > 0
let secret = text.to-int(line) catch 0
let added = list.append(secrets, secret)
secrets
# XOR of two values below 2^24, one bit at a time: a bit is set exactly when
# the operands disagree there.
word _xor24(a: Int, b: Int) -> Int
var result = 0
var place = 1
for bit in range(0, 24)
let left = (a / place) % 2
let right = (b / place) % 2
if left != right
result = result + place
place = place * 2
result
# One secret evolution: mix with secret*64, then secret/32, then
# secret*2048, pruning to 2^24 each time.
word _evolve(secret: Int) -> Int
let first = _xor24(secret, (secret * 64) % 16777216)
let second = _xor24(first, first / 32)
_xor24(second, (second * 2048) % 16777216)
## Sum of every buyer's 2000th secret number.
word part-one(secrets: List<Int>) -> Int
var total = 0
for secret in secrets
var current = secret
for step in range(0, 2000)
current = _evolve(current)
total = total + current
total
# Best total bananas: for each buyer, bank the price at the first occurrence
# of every four-change window, then take the largest window total.
word part-two(secrets: List<Int>) -> Int
let totals: Map<String, Int> = {}
for secret in secrets
let seen: Map<String, Bool> = {}
var current = secret
var prev = secret % 10
var d1 = 0
var d2 = 0
var d3 = 0
var d4 = 0
var count = 0
for step in range(0, 2000)
current = _evolve(current)
let price = current % 10
d1 = d2
d2 = d3
d3 = d4
d4 = price - prev
prev = price
count = count + 1
if count >= 4
let window = d1 + "," + d2 + "," + d3 + "," + d4
if not map.contains(seen, window)
let marked = map.put(seen, window, true)
var added = 0
match totals[window]
case Option.Some(bananas)
added = bananas
case Option.None
added = 0
totals[window] = added + price
var best = 0
for window, bananas in totals
if bananas > best
best = bananas
best
# Advent of Code 2024, day 22 — Monkey Market.
# Reads the initial secrets from stdin until end of input, prints both
# answers.
word main()
# shortcut: a secret is 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 secrets = parse(buffer.to-text(input))
print(part-one(secrets))
print(part-two(secrets))
Day 23LAN Party
The input lists connections between named computers, and connections run both ways. Part one asks how many sets of three computers have every pair connected, counting only sets that include at least one computer whose name starts with t. Part two asks for the largest group of computers with every pair connected, and the password is that group's names sorted and joined by commas.
Show solution
Output
7 co,de,ka,ta
# Advent of Code 2024, day 23 — LAN Party (solution words).
# Connections run both ways between two-letter computer names. Adjacency is
# a Map from name to a Map-as-set of neighbors; the name list is sorted once
# so ordered iteration replaces a visited set. Part 1 collects the connected
# triples that contain a t-chief into a set of sorted triple keys. Part 2
# grows cliques depth-first over the sorted names, extending each candidate
# only with later names adjacent to it — every clique appears once in sorted
# order, and the recursion depth is the clique size.
## Parse the connection lines.
word parse(text: String) -> List<String>
let edges: List<String> = []
for line in text.split(text, "\n")
if text.length(line) > 0
let added = list.append(edges, line)
edges
# One undirected edge into the adjacency map: endpoint sets both ways.
word _link(adj: Map<String, Map<String, Bool>>, a: String, b: String) -> Unit
var set: Map<String, Bool> = {}
match adj[a]
case Option.Some(neighbors)
set = neighbors
case Option.None
set = {}
let placed = map.put(set, b, true)
adj[a] = set
word _build-adj(edges: List<String>) -> Map<String, Map<String, Bool>>
let adj: Map<String, Map<String, Bool>> = {}
for edge in edges
let a = text.slice(edge, 0, 2)
let b = text.slice(edge, 3, 5)
_link(adj, a, b)
_link(adj, b, a)
adj
word _names(adj: Map<String, Map<String, Bool>>) -> List<String>
let names: List<String> = []
for name, connected in adj
let added = list.append(names, name)
list.sort(names)
word _connected(adj: Map<String, Map<String, Bool>>, a: String, b: String) -> Bool
match adj[a]
case Option.Some(neighbors)
map.contains(neighbors, b)
case Option.None
false
# A name's neighbor set; the empty set for a name with no links.
word _neighbors(adj: Map<String, Map<String, Bool>>, name: String) -> Map<String, Bool>
match adj[name]
case Option.Some(neighbors)
neighbors
case Option.None
{}
## Count the connected triples containing at least one t-chief.
word part-one(edges: List<String>) -> Int
let adj = _build-adj(edges)
let triples: Map<String, Bool> = {}
for name in _names(adj)
if text.starts-with(name, "t")
let neighbors = _neighbors(adj, name)
for first, mark in neighbors
for second, mark in neighbors
if first != second and _connected(adj, first, second)
let trio = list.sort([name, first, second])
let seen = map.put(triples, text.join(trio, ","), true)
map.length(triples)
word _copy(values: List<String>) -> List<String>
let out: List<String> = []
for value in values
let added = list.append(out, value)
out
# Depth-first clique growth: candidates stay sorted and mutually compatible
# with the clique, and each extension only takes later names, so every clique
# is visited once. Returns the larger of the best-so-far and what this branch
# found.
word _grow(adj: Map<String, Map<String, Bool>>, clique: List<String>, candidates: List<String>, best: List<String>) -> List<String>
var winner = best
if list.length(clique) > list.length(winner)
winner = clique
for index in range(0, list.length(candidates))
let name = candidates[index]
let next-clique = _copy(clique)
let added = list.append(next-clique, name)
let next-candidates: List<String> = []
for later in range(index + 1, list.length(candidates))
if _connected(adj, name, candidates[later])
let kept = list.append(next-candidates, candidates[later])
winner = _grow(adj, next-clique, next-candidates, winner)
winner
## The password: the largest all-connected group, sorted and comma-joined.
word part-two(edges: List<String>) -> String
let adj = _build-adj(edges)
let empty: List<String> = []
let best = _grow(adj, empty, _names(adj), empty)
text.join(best, ",")
# Advent of Code 2024, day 23 — LAN Party.
# Reads the connection list from stdin until end of input, prints both
# answers.
word main()
# shortcut: every line is a two-letter pair, 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 edges = parse(buffer.to-text(input))
print(part-one(edges))
print(part-two(edges))
Day 24Crossed Wires
The input holds starting wire values, then a list of AND, OR, and XOR gates, each reading two wires and writing one, with gates waiting for both inputs and no loops in the wiring. Part one asks for the decimal number formed by the bits on all wires whose names start with z, z00 being the least significant. Part two asks for the eight wire names of the four swapped gate-output pairs that break the system's binary-adder wiring — honestly pending, see the day's findings note.
Show solution
Output
2024 pending
# Advent of Code 2024, day 24 — Crossed Wires (solution words).
# Wires hold Bool values; AND, OR, and XOR gates wait for both inputs. Part 1
# evaluates the wiring to a fixpoint — gates fire once both inputs are known,
# passes repeat until nothing changes — and reads the z wires as a binary
# number, z00 least significant. Part 2 (finding the four swapped output
# pairs of the ripple-carry adder) resisted three structural solver designs
# in the Go oracle and stays pending: see docs/aoc-2024.md and the gap
# ticket.
type Circuit = record
values: Map<String, Bool>
ops: List<String>
lefts: List<String>
rights: List<String>
outs: List<String>
## Parse the wire values and the gate list.
word parse(text: String) -> Circuit
let values: Map<String, Bool> = {}
let ops: List<String> = []
let lefts: List<String> = []
let rights: List<String> = []
let outs: List<String> = []
for line in text.split(text, "\n")
if text.length(line) > 0
if text.contains(line, ":")
let colon = text.index-of(line, ":")
values[text.slice(line, 0, colon)] = text.slice(line, colon + 2, colon + 3) == "1"
else
let tokens = text.split(line, " ")
let added-left = list.append(lefts, tokens[0])
let added-op = list.append(ops, tokens[1])
let added-right = list.append(rights, tokens[2])
let added-out = list.append(outs, tokens[4])
Circuit(values, ops, lefts, rights, outs)
word _apply(op: String, a: Bool, b: Bool) -> Bool
if op == "AND"
a and b
elif op == "OR"
a or b
else
a != b
word _bool-at(known: Map<String, Bool>, key: String) -> Bool
match known[key]
case Option.Some(value)
value
case Option.None
false
# Every wire's value: known inputs first, then gates fire to a fixpoint.
word _evaluate(circuit: Circuit) -> Map<String, Bool>
let known: Map<String, Bool> = {}
for name, value in circuit.values
known[name] = value
var changed = true
while changed
changed = false
for index in range(0, list.length(circuit.ops))
if not map.contains(known, circuit.outs[index])
if map.contains(known, circuit.lefts[index]) and map.contains(known, circuit.rights[index])
known[circuit.outs[index]] = _apply(circuit.ops[index], _bool-at(known, circuit.lefts[index]), _bool-at(known, circuit.rights[index]))
changed = true
known
## The decimal number on the z wires, z00 least significant.
word part-one(circuit: Circuit) -> Int
let known = _evaluate(circuit)
let zs: List<String> = []
for name, value in known
if text.starts-with(name, "z")
let added = list.append(zs, name)
let ordered = list.sort(zs)
var total = 0
var place = 1
for name in ordered
if _bool-at(known, name)
total = total + place
place = place * 2
total
# Advent of Code 2024, day 24 — Crossed Wires.
# Reads the wiring from stdin until end of input, prints part one's answer;
# part two (the four swapped output pairs of the ripple-carry adder) is
# honestly pending — see docs/aoc-2024.md day 24 and its gap ticket.
word main()
# shortcut: wire lines never match this sentinel; 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 circuit = parse(buffer.to-text(input))
print(part-one(circuit))
print "pending"
Day 25Code Chronicle
The input holds schematics of locks, whose top row is filled, and keys, whose bottom row is filled, and each schematic reads as five column heights. A key fits a lock when, in every column, the lock's height and the key's height together stay within the available space. Part one asks how many lock and key pairs fit. Part two is the event's finale: with every other star collected the fiftieth arrives on its own, and the customary answer is the star itself.
Show solution
Output
3 *
# Advent of Code 2024, day 25 — Code Chronicle (solution words).
# Each schematic is seven rows of five columns: a solid border row, five
# working rows, and the opposite border. A lock's pins hang from the top, a
# key's rise from the bottom; either way a column's height is its # count in
# the five working rows. A lock and key pair fits when every column's two
# heights sum to at most five. Part 2 is the event's finale: with every other
# star collected the fiftieth arrives on its own, so the answer is the star.
type Schematics = record
locks: List<List<Int>>
keys: List<List<Int>>
# One schematic's five column heights.
word _heights(group: List<String>) -> List<Int>
let heights: List<Int> = []
for column in range(0, 5)
var count = 0
for row in range(1, 6)
if text.slice(group[row], column, column + 1) == "#"
count = count + 1
let added = list.append(heights, count)
heights
# File one finished schematic: the top border full of # makes a lock.
word _take(group: List<String>, locks: List<List<Int>>, keys: List<List<Int>>) -> Unit
if list.length(group) == 7
if text.slice(group[0], 0, 1) == "#"
let added = list.append(locks, _heights(group))
else
let added = list.append(keys, _heights(group))
## Split the schematics apart and read their column heights.
word parse(text: String) -> Schematics
let locks: List<List<Int>> = []
let keys: List<List<Int>> = []
var group: List<String> = []
for line in text.split(text, "\n")
if text.length(line) == 0
_take(group, locks, keys)
group = []
else
let added = list.append(group, line)
_take(group, locks, keys)
Schematics(locks, keys)
# Whether one lock and key pair leave every column within the five rows.
word _fits(lock: List<Int>, key: List<Int>) -> Bool
var fits = true
for column in range(0, 5)
if lock[column] + key[column] > 5
fits = false
fits
## How many lock and key pairs fit.
word part-one(schematics: Schematics) -> Int
var total = 0
for lock in schematics.locks
for key in schematics.keys
if _fits(lock, key)
total = total + 1
total
## The finale star: collected, not computed.
word part-two(schematics: Schematics) -> String
"*"
# Advent of Code 2024, day 25 — Code Chronicle.
# Reads the schematics from stdin until end of input, prints both answers.
word main()
# shortcut: schematic rows are # 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 schematics = parse(buffer.to-text(input))
print(part-one(schematics))
print(part-two(schematics))
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.
Show solution
Output
3 6
# 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.
Show solution
Output
1227775554 4174379265
# 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.
Show solution
Output
357 3121910778619
# 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.
Show solution
Output
13 43
# 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.
Show solution
Output
3 14
# 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.
Show solution
Output
4277556 3263827
# 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.
Show solution
Output
21 40
# 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.
Show solution
Output
40 25272
# 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.
Show solution
Output
50 24
# 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.
Show solution
Output
7 33
# 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.
Show solution
Output
5 0
# 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.
Show solution
Output
2 *
# 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))