aoc.gabber235.dev

Day 3

kotlin
puzzle ↗

bench

v2 is the fastest

part 1

628 µs

608 µs 866 µs

rewrites

v1
2.8xv2
fastest

warm-up 3.6x faster once warm

697 KB allocated per run

part 2

7.56 ms

7.44 ms 9.24 ms

rewrites

v1
16.1xv2
fastest

warm-up 1.4x faster once warm

1.1 MB allocated per run

code · v2

2026/days/day03/v2/Day03.kt
package day03.v2

import aoc.Grid
import aoc.Input
import aoc.Point
import aoc.grid
import aoc.solve

enum class Place {
    Ground,
    Tree,
}

fun Char.toPlace(): Place = when (this) {
    '.' -> Place.Ground
    '#' -> Place.Tree
    else -> throw IllegalArgumentException("Could not convert")
}

fun Grid<Place>.isTree(point: Point) = getOrNull(point) == Place.Tree

fun Grid<Place>.treeSquare(startPoint: Point, size: Int): Boolean {
    return isTree(startPoint + Point(size, 0))
            && isTree(startPoint + Point(0, size))
            && isTree(startPoint + Point(size, size))
}

fun Grid<Place>.treeSquares(startPoint: Point): Int {
    val maxSize = minOf(this.width - startPoint.x, this.height - startPoint.y)
    return (1..maxSize).count { treeSquare(startPoint, it) }
}

fun part1(input: String): Int {
    val grid = input.grid().map { _, ch -> ch.toPlace() }
    return grid.findAll(Place.Tree).sumOf { grid.treeSquares(it) }
}

fun part2(input: String): Int {
    val grid = input.grid().map { _, ch -> ch.toPlace() }
    return grid.findAll(Place.Tree).sumOf { grid.treeRotatedSquares(it) }
}

fun Grid<Place>.treeSquare(startPoint: Point, size: Int, rotation: Int): Boolean {
    return isTree(startPoint + Point(size-rotation, rotation))
            && isTree(startPoint + Point(size - 2*rotation, size))
            && isTree(startPoint + Point( - rotation, size - rotation))
}


fun Grid<Place>.treeRotatedSquares(startPoint: Point): Int {
    val maxSize = this.height - startPoint.y
    var count = 0
    for (size in 1..maxSize) {
        val startRotation = maxOf(0, size - (this.width - startPoint.x))
        val endRotation = minOf(size-1, startPoint.x)
        for (rotation in startRotation .. endRotation) {
            if (treeSquare(startPoint, size, rotation)) {
                count++
            }
        }
    }
    return count
}

fun main() = solve(3, version = 2)
Puzzles by Eric Wastl at adventofcode.com · solutions and benchmarks by gabber235