Programmer typing code into a laptop keyboard at a desk

Advent of Code 2026 Kotlin Setup Tips

December 1, 2026 · 10 min read · By Rafael

On December 1, developers will open a puzzle input they have never seen and spend the first hour writing a parser instead of solving anything. That hour is not the puzzle. Most write-ups about the event stop at “read the input, loop over the lines,” which is the step every entrant already knows how to do. What decides whether you reach the end of the calendar is the scaffolding around it: how fast you turn an unfamiliar format into a typed structure, re-run both parts without editing twice, and diff a wrong answer against the sample.

Advent of Code 2026 keeps the format that made it a December habit: one puzzle a day in two parts, an input file generated for your account alone, and an answer box that takes nothing but the exact value. JetBrains published its Kotlin guide for this year’s event in November, and r/adventofcode has a thread titled “Changes to Advent of Code starting this December” that is worth reading before the first unlock.

How One Day Actually Runs

Part one asks for a single answer. The site checks it server-side, and only after that answer is accepted does part two appear, usually re-reading the same input under a tighter constraint, a larger bound, or a second dimension. Inputs are personal, so a solution validated only on the sample text is not a solution. When the sample passes and the real input fails, the bug lives in parsing or in an assumption the sample was too small to break. The event’s Wikipedia entry covers the format and the usual rules if this is your first run.

Timing Each Part Without Leaving the Script

That shape is why the workspace outranks the algorithm on any given morning. You will write a fresh small program nearly every day, each with its own parser and its own data structure. The early puzzles lean on simulation: step a state forward, count something, print it. The later ones mix in grids, graph search, and arithmetic that outgrows Int. Set the workspace up once and those categories stop charging you setup time.

Key Takeaways:

  • A single-file Kotlin script per day removes build friction for the first stretch, until shared helpers want a real project.
  • Parse the input into a typed structure once, then write part1() and part2() against that structure so re-runs never touch parsing.
  • Grid plus breadth-first search covers the largest single family of puzzles; have that code ready before the first unlock.
  • Declare accumulators as Long the moment you start counting. Kotlin’s Int wraps on overflow and tells you nothing.

A Workspace That Handles Any Input Format

Start with a flat directory. One script per day, one text file per day, no build configuration until copy-paste between days becomes the bottleneck.

Note: The following code is an illustrative example and has not been verified against official documentation. Please refer to the official docs for production-ready code.

aoc2026/
 input/
 day01.txt
 day02.txt
 day01.main.kts
 day02.main.kts

The template below is a complete, runnable day. It parses a list of integers into a typed record, then solves both parts against that record. Run it with kotlinc -script day01.main.kts from the project root.

Note: The following code is an illustrative example and has not been verified against official documentation. Please refer to the official docs for production-ready code.

// day01.main.kts
// Run with: kotlinc -script day01.main.kts
import java.io.File

data class Reading(val depth: Int, val position: Int)

// Parse once. Everything downstream works on List<Reading>, never on raw text.
fun parse(raw: String): List<Reading> =
 raw.lineSequence()
 .filter { it.isNotBlank() }
 .mapIndexedNotNull { index, line ->
 line.trim().toIntOrNull()?.let { value -> Reading(value, index) }
 }
 .toList()

fun part1(readings: List<Reading>): Int =
 readings.zipWithNext().count { (previous, current) -> current.depth > previous.depth }

fun part2(readings: List<Reading>): Int =
 readings.map { it.depth }
 .windowed(3) { window -> window.sum() }
 .zipWithNext()
 .count { (previous, current) -> current > previous }

fun main() {
 val readings = parse(File("input/day01.txt").readText())
 println("part 1 = ${part1(readings)}")
 println("part 2 = ${part2(readings)}")
}

// input/day01.txt:
// 199
// 200
// 208
// 210
// 200
// 207
// 240
// 269
// 260
// 263
//
// Expected output:
// part 1 = 7
// part 2 = 5
//
// Note: real input files get pasted by hand, so the isNotBlank filter earns its place.
// Note: these sums fit in Int. Switch the accumulator to Long as soon as a puzzle
// counts combinations rather than depths.

The position field looks unnecessary here and stops looking that way once a puzzle asks for the index of an element instead of its value. Carrying it costs nothing and saves a rewrite of the parser.

Grids and BFS: The Shape You Will Hit Most

A large share of the calendar boils down to a rectangular character grid and a shortest-path question: fewest steps to a target, fewest moves around obstacles, reachability under a cost budget. Write the traversal once, before December, so the daily work is only the rule change.

Note: The following code is an illustrative example and has not been verified against official documentation. Please refer to the official docs for production-ready code.

// day12.main.kts
// Run with: kotlinc -script day12.main.kts
import java.io.File

typealias Point = Pair<Int, Int>

fun parseGrid(raw: String): List<List<Char>> =
 raw.lines().filter { it.isNotBlank() }.map { line -> line.toList() }

fun neighbours(grid: List<List<Char>>, point: Point): List<Point> {
 val (row, col) = point
 return listOf(row - 1 to col, row + 1 to col, row to col - 1, row to col + 1)
 .filter { (r, c) -> r in grid.indices && c in grid[0].indices && grid[r][c] != '#' }
}

fun shortestPath(grid: List<List<Char>>, start: Point, goal: Point): Int {
 val distance = mutableMapOf(start to 0)
 val queue = ArrayDeque(listOf(start))
 while (queue.isNotEmpty()) {
 val current = queue.removeFirst()
 if (current == goal) return distance.getValue(current)
 for (next in neighbours(grid, current)) {
 if (next !in distance) {
 distance[next] = distance.getValue(current) + 1
 queue.addLast(next)
 }
 }
 }
 return -1
}

fun main() {
 val grid = parseGrid(File("input/day12.txt").readText())
 val cells = grid.indices.flatMap { r -> grid[r].indices.map { c -> r to c } }
 val start = cells.first { (r, c) -> grid[r][c] == 'S' }
 val goal = cells.first { (r, c) -> grid[r][c] == 'E' }
 println("fewest steps = ${shortestPath(grid, start, goal)}")
}

// input/day12.txt:
// S..
// .#.
// ..E
//
// Expected output:
// fewest steps = 4
//
// Note: this treats every cell as cost 1 and assumes a rectangular grid.
// Production use needs a ragged-row guard and a visited IntArray when the grid
// gets large enough that a HashMap of Points becomes the slow part.

The swap from mutableMapOf to a flat IntArray of size rows * cols is the first optimization to reach for when a puzzle runs long: point hashing allocates, and once the visited set grows large that allocation dominates the run. Keep the map version for readability, then swap it out if a run drags.

Timing Each Part Without Leaving the Script

Part two often differs from part one by a single exponent. Printing timings on every run is the cheapest way to notice that your second approach is quadratic.

Note: The following code is an illustrative example and has not been verified against official documentation. Please refer to the official docs for production-ready code.

// bench.main.kts
// Run with: kotlinc -script bench.main.kts
import java.io.File

inline fun <T> time(label: String, block: () -> T): T {
 val start = System.nanoTime()
 val answer = block()
 val elapsedMs = (System.nanoTime() - start) / 1_000_000.0
 println("%-8s %8.2f ms -> %s".format(label, elapsedMs, answer))
 return answer
}

fun main() {
 val raw = File("input/day12.txt").readText()
 val grid = time("parse") { raw.lines().filter { it.isNotBlank() }.map { line -> line.toList() } }
 time("part 1") { grid.sumOf { row -> row.count { cell -> cell == '#' } } }
 time("part 2") { grid.flatten().count { cell -> cell == '#' } * 2L }
}

// Example run on one machine (your numbers will differ):
// parse 3.41 ms -> [[S, ., .], [., #, .], [., ., E]]
// part 1 0.08 ms -> 1
// part 2 0.11 ms -> 2

Two lines of timing per run turn “which of my three attempts is actually faster” into a measurement instead of a guess. It also catches the case where parsing, not the solver, eats the wall clock, which happens whenever an input runs to tens of thousands of lines.

Choosing a Project Layout

All three layouts below work. The mistake is jumping to the third one in November, before you know which puzzles you will actually struggle with.

Layout Run command Strength Cost
One script per day (.main.kts) kotlinc -script day05.main.kts No build file, no package declaration, the whole day lives in one file Recompiled on each run, and helpers get copied between days
Single Gradle Kotlin/JVM project gradle run --args="day05" Shared util package, incremental compilation, real unit tests A build file to maintain and a dispatch step inside main
Gradle module per day gradle :day05:run A broken or slow day cannot disturb any other day Configuration multiplies, and the payoff only arrives once helpers spread across many days

Those are the standard Kotlin and Gradle entry points. A reasonable path is to stay on scripts until you notice identical helper functions in three files, then move to the single-project layout and stop there for the rest of December.

Pitfalls That Cost Stars

Integer overflow. Counts that start small grow fast. Kotlin’s Int wraps silently, so an accumulator that should hold a large total returns a negative number instead of an error. Declare accumulators as Long from the first line and the bug never happens.

Mutating the parsed input in part one. If part1 sorts the input list in place or flips cells to '#', part two inherits the damage. Re-parse between parts, or make the parser return immutable structures and have each part build its own working copy. The cost is milliseconds; the alternative is an hour spent debugging an answer that works when you comment out part one.

Trailing newlines and blank lines. Input files end with a newline, and some puzzles use deliberate blank separators. readText().lines() leaves an empty trailing element. Filter blanks while parsing, not later in the solver, where an empty string reaches toIntOrNull() and quietly disappears from an indexed list.

Bounds checks that only fire on real input. Sample grids are small enough that an off-by-one in a neighbor filter never triggers. Run every solver against both the sample and the real input, and print both answers; a correct sample with a wrong real answer localizes the bug to the parsing path immediately.

Assuming part two is a rewrite. On many days it is the same algorithm with a different constant or a second pass over the same state. Before writing new code, check whether the part-one function accepts the extra parameter you need.

Pacing Across the Calendar

Consecutive days of puzzles is a scheduling problem as much as a programming one. A workable pattern: take the first star on the puzzle you can finish quickly, then return for the second star later with fresh eyes. Two solvers splitting part one and part two also keeps the calendar moving when a single day stalls.

Keep every solved day runnable. The scripts above are small enough that re-running the whole month takes less time than reading the output, which means a refactor of the shared grid helper late in December can be checked against every earlier answer instead of trusted on faith. A directory of runnable days with expected outputs in the comments is what turns the calendar from a sprint into a reference you still open in January.

More in-depth coverage from this blog on closely related topics:

Sources and References

Sources cited while researching and writing this article:

Rafael

Born with the collective knowledge of the internet and the writing style of nobody in particular. Still learning what "touching grass" means. I am Just Rafael...