290 tokens in Kotlin for part 2 by Valentin Slawicek
Download solution
data
class
Card
(
val
cardNumber
:
Int
,
val
winningNumbers
:
Set
<
Int
>
,
val
numbersYouHave
:
Set
<
Int
>
)
fun
main
(
)
{
val
cards
=
generateSequence
(
::
readLine
)
.
map
{
line
->
val
cardNumber
=
line
.
substringBefore
(
"
:
"
)
.
substringAfterLast
(
"
"
)
.
toInt
(
)
val
winningNumbers
=
line
.
substringAfter
(
"
:
"
)
.
substringBefore
(
"
|
"
)
.
split
(
"
"
)
.
mapNotNull
{
number
->
number
.
trim
(
)
.
takeIf
{
it
.
isNotEmpty
(
)
}
?.
toInt
(
)
}
val
numbersYouHave
=
line
.
substringAfter
(
"
|
"
)
.
split
(
"
"
)
.
mapNotNull
{
number
->
number
.
trim
(
)
.
takeIf
{
it
.
isNotEmpty
(
)
}
?.
toInt
(
)
}
Card
(
cardNumber
,
winningNumbers
.
toSet
(
)
,
numbersYouHave
.
toSet
(
)
)
}
val
cardsToMatches
:
Map
<
Card
,
Int
>
=
cards
.
associateWith
{
it
.
winningNumbers
.
intersect
(
it
.
numbersYouHave
)
.
count
(
)
}
val
cardCount
:
MutableMap
<
Int
,
Int
>
=
cardsToMatches
.
keys
.
map
{
it
.
cardNumber
}
.
associateWith
{
1
}
.
toMutableMap
(
)
cardsToMatches
.
forEach
{
(
card
,
matches
)
->
(
card
.
cardNumber
+
1
..
card
.
cardNumber
+
matches
)
.
forEach
{
nextCardNumber
->
cardCount
[
nextCardNumber
]
=
cardCount
[
nextCardNumber
]
!!
+
cardCount
[
card
.
cardNumber
]
!!
}
}
println
(
cardCount
.
values
.
sum
(
)
)
}