Problem 14

This commit is contained in:
2026-03-19 15:39:29 +01:00
parent f1be55948f
commit 8db078f6b6
2 changed files with 35 additions and 0 deletions
@@ -0,0 +1,18 @@
package ninetyNineScalaProblems
import scala.annotation.tailrec
object Problem14:
def duplicateElements(list: List[Any]): List[Any] =
@tailrec
def loop(cursor: List[Any], acc: List[Any]): List[Any] =
cursor match
case e :: tail =>
loop(tail, e :: e :: acc)
case Nil =>
acc
loop(list, List()).reverse
def duplicateElements2(list: List[Any]): List[Any] =
list.flatMap(i => i :: List(i))
@@ -0,0 +1,17 @@
package ninetyNineScalaProblems
import scala.compiletime.ops.boolean
class Problem14Suite extends munit.FunSuite:
List(
(List(1, 2, 3, 4), List(1, 1, 2, 2, 3, 3, 4, 4)),
(List(1, 2, 2, 3), List(1, 1, 2, 2, 2, 2, 3, 3)),
(List(1, 2, 3, 2), List(1, 1, 2, 2, 3, 3, 2, 2)),
(List(), List()),
(List(1), List(1, 1)),
(List(1, 1, 1), List(1, 1, 1, 1, 1, 1)),
).foreach:
case (list, expected) =>
test(s"duplicateElements returns [$expected]"):
assertEquals(Problem14.duplicateElements(list), expected)
assertEquals(Problem14.duplicateElements2(list), expected)