# 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
```) {
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
println(result)
}
}
fun withFile(filename: String, block: (CPointer) -> T): T {
val fd = fopen(filename, "r")
if (fd != null) {
val ret = block(fd)
fclose(fd)
return ret
} else {
throw AssertionError("File not found: $filename")
}
}