The challenge

The captcha requires you to review a sequence of digits (your puzzle input) and find the sum of all digits that match the next digit in the list. The list is circular, so the digit after the last digit is the first digit in the list.

For example:

  • 1122 produces a sum of 3 (1 + 2) because the first digit (1) matches the second digit and the third digit (2) matches the fourth digit.
  • 1111 produces 4 because each digit (all 1) matches the next.
  • 1234 produces 0 because no digit matches the next.
  • 91212129 produces 9 because the only digit that matches the next one is the last digit, 9.

My Logic

I keep track of the first item, the last seen item and the total. I pass over the list, adding the items that match the last seen item. I handle the first digit by adding the first to the total if it matches the last of the list.

import kotlinx.cinterop.*
import platform.posix.*

const val FILEPATH = "data.dat"
const val ZERO_CODEPOINT = '0'.toInt()

fun main(args: Array<String>) {
    withFile(FILEPATH) { fd ->
        val (first, last, total) = generateSequence {
            val value = fgetc(fd)
            when (value) {
                -1 -> null
                else -> value
            .map { it - ZERO_CODEPOINT }
            .foldIndexed(listOf(-1, -1, 0)) { index, (first, last, total), value ->
                val newTotal = if (last == value) total + value else total
                val newFirst = if (first == -1) value else first
                listOf(newFirst, value, newTotal)

        val result = if (first == last) total + first else total
fun <T> withFile(filename: String, block: (CPointer<FILE>) -> T): T {
    val fd = fopen(filename, "r")
    if (fd != null) {
        val ret = block(fd)
        return ret
    } else {
        throw AssertionError("File not found: $filename")

2 Answers 2


foldIndexed -> fold

The foldIndexed line can be replaced with:

.fold(Carry(-1, -1, 0)) { (first, last, total), value ->

This is because the indexed part is unused

Using a data class

A data class can be used to make the values passed along the fold operation more obvious.


Assuming you already have input integer you can use provided functions to solve the task.

fun digitSum(input: Long): Int {
    val digits = input.toString().map { it.toString().toInt() }
    val circularDigigs = if (digits.size > 2) digits + digits.first() else digits
    val pairs = circularDigigs.zipWithNext().filter { (it, next) -> it == next }
    return pairs.sumBy { (it, _) -> it }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.