@AoKSolution object Day04BitSet { inline fun buildBitSet(size: Int = 64, build: BitSet.() -> Unit) = BitSet(size).apply(build) operator fun BitSet.iterator() = object : IntIterator() { var at = nextSetBit(0) override fun nextInt(): Int = at.also { at = nextSetBit(it + 1) } override fun hasNext(): Boolean = at >= 0 } class BitGrid( val rolls: BitSet, val width: Int ) { fun neighbours(at: Int): Int { var c = 0 visitNeighbours(at) { c++ } return c } inline fun visitNeighbours(at: Int, f: (Int) -> Unit) { var it = at - width - 1 if (rolls[it]) f(it) if (rolls[++it]) f(it) if (rolls[++it]) f(it) it += width if (rolls[it]) f(it) it -= 2 if (rolls[it]) f(it) it += width if (rolls[it]) f(it) if (rolls[++it]) f(it) if (rolls[++it]) f(it) } } fun parse(input: String): BitGrid { val width = input.indexOf('\n') + 1 val offset = width + 1 // avoid needing to check for negatives when visiting neighbours val rolls = buildBitSet { for ((i, char) in input.withIndex()) { if (char == '@') set(i + offset) } } return BitGrid(rolls, width) } context(_: PuzzleInput) fun part1() = with(parse(input)) { var c = 0 for (roll in rolls) if (neighbours(roll) < 4) c++ c } context(_: PuzzleInput) fun part2() = with(parse(input)) { val removed = buildBitSet { for (roll in rolls) if (neighbours(roll) < 4) set(roll) }.also(rolls::andNot) var total = removed.cardinality() while (!removed.isEmpty) { var next = removed.nextSetBit(0) while (next >= 0) { removed.clear(next) visitNeighbours(next) { roll -> if (neighbours(roll) < 4) { rolls.clear(roll) removed.set(roll) next = roll total++ } } next = removed.nextSetBit(next) } } total } }