Mikael Ståldal
12/31/2022, 1:53 PMString::split
for input parsing in e.g. day 2, day 4 and day 9?
In Scala there is pattern patching on string templates and regular expressions. Do we have anything like that in Kotlin?Vampire
12/31/2022, 3:14 PMString::split
(or actually Charsequence::split
) also has a variant taking regex or pattern, isn't that what you are after?Mikael Ståldal
12/31/2022, 3:19 PMVampire
12/31/2022, 3:25 PMMikael Ståldal
12/31/2022, 4:03 PMephemient
12/31/2022, 4:23 PMephemient
12/31/2022, 4:24 PMephemient
12/31/2022, 4:58 PMmaiatoday
12/31/2022, 9:29 PMsubstringBefore
and `substringAfter`and this blog postSergei Petunin
01/01/2023, 12:18 PMval inputLineRegex = """(\d+),(\d+) -> (\d+),(\d+)""".toRegex()
val (startX, startY, endX, endY) = inputLineRegex
.matchEntire(s)
?.destructured
?: throw IllegalArgumentException("Incorrect input line $s")
The problem with this code is, startX
, startY
etc. will be Strings
, and you'll have to manually convert them to Int
. So the destructured
property of the MatchResult
is a step in the right direction, but it's still pretty messy. What I would like to do is to declaratively say: here's a template, here's where the variables in this template are, here are their types, please parse.
So hear me out. What if Day 4 part 1 could look like this:
fun part1(input: String) = input.lines().count { "${from1:Int},${to1:Int}-${from2:Int},${to2:Int}" ->
from1 <= from2 && to1 >= to2 || from1 >= from2 && to1 <= to2 }
elizarov
01/09/2023, 8:16 AM