408 tokens in Kotlin for part 1 by Valentin Slawicek
Download solution
data
class
MapEntry
(
val
source
:
String
,
val
destination
:
String
,
val
sourceStart
:
Long
,
val
destinationStart
:
Long
,
val
rangeLength
:
Long
)
{
val
sourceRange
=
LongRange
(
sourceStart
,
sourceStart
+
rangeLength
-
1
)
}
fun
main
(
)
{
val
mapEntries
=
mutableListOf
<
MapEntry
>
(
)
var
seeds
:
List
<
Long
>
=
emptyList
(
)
var
currentMap
=
"
"
to
"
"
generateSequence
(
::
readLine
)
.
forEach
{
line
->
when
{
line
.
startsWith
(
"
s
e
e
d
s
:
"
)
->
{
seeds
=
line
.
substringAfter
(
"
s
e
e
d
s
:
"
)
.
split
(
"
"
)
.
map
{
it
.
toLong
(
)
}
}
line
.
endsWith
(
"
m
a
p
:
"
)
->
{
currentMap
=
line
.
substringBefore
(
"
-
"
)
to
line
.
substringAfter
(
"
-
t
o
-
"
)
.
substringBefore
(
"
"
)
}
line
.
isEmpty
(
)
->
Unit
else
->
{
val
mapEntryString
=
line
.
split
(
"
"
)
.
map
{
it
.
toLong
(
)
}
mapEntries
+=
MapEntry
(
source
=
currentMap
.
first
,
destination
=
currentMap
.
second
,
destinationStart
=
mapEntryString
[
0
]
,
sourceStart
=
mapEntryString
[
1
]
,
rangeLength
=
mapEntryString
[
2
]
)
}
}
}
fun
getMapEntry
(
source
:
String
,
number
:
Long
)
:
MapEntry
{
return
mapEntries
.
singleOrNull
{
it
.
source
==
source
&&
it
.
sourceStart
<=
number
&&
it
.
sourceStart
+
it
.
rangeLength
>
number
}
?:
mapEntries
.
first
{
it
.
source
==
source
}
.
copy
(
sourceStart
=
number
,
destinationStart
=
number
,
rangeLength
=
1
)
}
fun
resolve
(
source
:
String
,
number
:
Long
)
:
Long
{
val
mapEntry
=
getMapEntry
(
source
,
number
)
val
destinationNumber
=
mapEntry
.
destinationStart
+
number
-
mapEntry
.
sourceStart
return
if
(
mapEntry
.
destination
==
"
l
o
c
a
t
i
o
n
"
)
{
destinationNumber
}
else
{
resolve
(
mapEntry
.
destination
,
destinationNumber
)
}
}
println
(
seeds
.
minOf
{
resolve
(
"
s
e
e
d
"
,
it
)
}
)
}