I have 2 Lists containing lottery-ticket instances.
One List holds tickets that won a special prize, the other List contains Tickets that got final-digit-hits.
Now I have to eliminate those tickets with redundant numbers and add the prizes together.
case class Ticket(number:Long, prize:Long)
val specialPrizes = List(Ticket(42, 1000), Ticket(66, 2000))
val finalDigitPrizes = List(Ticket(42, 50))
This would yield a List with merged Tickets which themselves contain accumulated prizes:
val finalList = List(Ticket(42, 1050), Ticket(66, 2000))
What would be the most effective way to do this functionally without temp-vars, index-counters, etc?
scala> (specialPrizes ++ finalDigitPrizes).groupBy(_.number).map {
| case (n, ts) => Ticket(n, ts.map(_.prize).sum)
| }
res1: scala.collection.immutable.Iterable[Ticket] = List(Ticket(42,1050), Ticket(66,2000))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With