For those of you who write up utility functions, w...
# advent-of-code
n
For those of you who write up utility functions, which are your favorites? Mine is:
fun String.getInts(): Sequence<Int>
, which finds all the
Ints
in a
String
. Perfect for quick parsing of so many AoC inputs. Day4 uses
line.getInts().drop(1)
. Often you don't need to even split your input into lines, just run
getInts().chunked(n, ::transform)
.
K 4
🙌🏼 1
🙌 2
The version I use is found here, but is a little too generalized for quick inspection. A perfectly usable version can be done in two lines:
Copy code
private val intRx = Regex("""(?<!\d)-?\d+""")
fun String.getInts() = intRx.findAll(this).mapNotNull { it.value.toIntOrNull() }
🙏 1
p
I tend to use
Copy code
fun String.splitIntsNotNull(vararg delimiters: String = arrayOf(" ")) = split(*delimiters).mapNotNull(String::toIntOrNull)
🙏 1
p
after today’s input my favourite is
fun List<String>.chunkedByEmptyLine()
n
Yeah, I combined those two for today's puzzle.
a
In day 4 I was using
Copy code
val (id, a, b) = card.findIntNumbers().splitBy(setOf(1, 11))
n
what does splitBy look like? Are you hardcoding the number of digits to split at?
a
Copy code
fun <T> List<T>.splitBy(idx: Set<Int>) = foldIndexed(mutableListOf<MutableList<T>>()) { i, list, v ->
    if (idx.contains(i) || list.isEmpty()) list.add(mutableListOf(v)) else list.last().add(v)
    list
}
👍 1