https://kotlinlang.org logo
#advent-of-code
Title
# advent-of-code
n

Neil Banman

12/04/2023, 5:56 PM
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

phldavies

12/04/2023, 6:56 PM
I tend to use
Copy code
fun String.splitIntsNotNull(vararg delimiters: String = arrayOf(" ")) = split(*delimiters).mapNotNull(String::toIntOrNull)
🙏 1
p

Pawel Matysek

12/05/2023, 8:50 AM
after today’s input my favourite is
fun List<String>.chunkedByEmptyLine()
n

Neil Banman

12/05/2023, 7:55 PM
Yeah, I combined those two for today's puzzle.
a

Andrei Kovalevsky

12/05/2023, 9:48 PM
In day 4 I was using
Copy code
val (id, a, b) = card.findIntNumbers().splitBy(setOf(1, 11))
n

Neil Banman

12/05/2023, 10:33 PM
what does splitBy look like? Are you hardcoding the number of digits to split at?
a

Andrei Kovalevsky

12/06/2023, 7:16 AM
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
7 Views