Problem 10

This commit is contained in:
2026-03-19 15:39:23 +01:00
parent 7e6ea14b44
commit 787e55eb85
2 changed files with 32 additions and 0 deletions
@@ -0,0 +1,15 @@
package ninetyNineScalaProblems
import scala.annotation.tailrec
object Problem10:
def runLengthEncode(list: List[Any]): List[Tuple2[Int, Any]] =
@tailrec
def loop(cursor: List[List[Any]], acc: List[Tuple2[Int, Any]]): List[Tuple2[Int, Any]] =
cursor match
case d :: tail =>
loop(tail, (d.length, d(0)) :: acc)
case Nil =>
acc
loop(Problem09.consecutiveDuplicatesIntoSublists(list), List()).reverse
@@ -0,0 +1,17 @@
package ninetyNineScalaProblems
import scala.compiletime.ops.boolean
class Problem10Suite extends munit.FunSuite:
List(
(List(1, 2, 3, 4), List((1, 1), (1, 2), (1, 3), (1, 4))),
(List(1, 2, 2, 3), List((1, 1), (2, 2), (1, 3))),
(List(1, 2, 3, 2), List((1, 1), (1, 2), (1, 3), (1, 2))),
(List(), List()),
(List(1), List((1, 1))),
(List(1, 1, 1), List((3, 1))),
(List(1, 1, 1, 1, 2, 3, 3, 1, 1, 4, 5, 5, 5, 5), List((4, 1), (1,2), (2, 3), (2, 1), (1, 4), (4, 5)))
).foreach:
case (list, expected) =>
test(s"runLengthEncoding returns [$expected]"):
assertEquals(Problem10.runLengthEncode(list), expected)