Problem 15
This commit is contained in:
@@ -0,0 +1,29 @@
|
|||||||
|
package ninetyNineScalaProblems
|
||||||
|
|
||||||
|
import scala.annotation.tailrec
|
||||||
|
|
||||||
|
object Problem15:
|
||||||
|
def fillList(value: Any, repititions: Int): List[Any] =
|
||||||
|
@tailrec
|
||||||
|
def loop(cursor: Int, acc: List[Any]): List[Any] =
|
||||||
|
cursor match
|
||||||
|
case c if c > 0 =>
|
||||||
|
loop(cursor - 1, value :: acc)
|
||||||
|
case 0 =>
|
||||||
|
acc
|
||||||
|
|
||||||
|
loop(repititions, List())
|
||||||
|
|
||||||
|
def duplicateElementsTimes(times: Int, list: List[Any]): List[Any] =
|
||||||
|
@tailrec
|
||||||
|
def loop(cursor: List[Any], acc: List[Any]): List[Any] =
|
||||||
|
cursor match
|
||||||
|
case e :: tail =>
|
||||||
|
loop(tail, fillList(e, times) ::: acc)
|
||||||
|
case Nil =>
|
||||||
|
acc
|
||||||
|
|
||||||
|
loop(list, List()).reverse
|
||||||
|
|
||||||
|
def duplicateElementsTimes2(times: Int, list: List[Any]): List[Any] =
|
||||||
|
list.flatMap(i => List.fill(times)(i))
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package ninetyNineScalaProblems
|
||||||
|
|
||||||
|
import scala.compiletime.ops.boolean
|
||||||
|
|
||||||
|
class Problem15Suite extends munit.FunSuite:
|
||||||
|
List(
|
||||||
|
((0, List(1, 2, 3, 4)), List()),
|
||||||
|
((1, List(1, 2, 3, 4)), List(1, 2, 3, 4)),
|
||||||
|
((2, List(1, 2, 3, 4)), List(1, 1, 2, 2, 3, 3, 4, 4)),
|
||||||
|
((3, List(1, 2, 3, 4)), List(1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4)),
|
||||||
|
((0, List()), List()),
|
||||||
|
((1, List()), List()),
|
||||||
|
((2, List()), List()),
|
||||||
|
((3, List()), List()),
|
||||||
|
((0, List(1)), List()),
|
||||||
|
((1, List(1)), List(1)),
|
||||||
|
((2, List(1)), List(1, 1)),
|
||||||
|
((3, List(1)), List(1, 1, 1)),
|
||||||
|
).foreach:
|
||||||
|
case ((times, list), expected) =>
|
||||||
|
test(s"duplicateElementsTimes returns [$expected]"):
|
||||||
|
assertEquals(Problem15.duplicateElementsTimes(times, list), expected)
|
||||||
|
assertEquals(Problem15.duplicateElementsTimes2(times, list), expected)
|
||||||
|
|
||||||
|
List(
|
||||||
|
((0, 1), List()),
|
||||||
|
((0, 0), List()),
|
||||||
|
((1, 1), List(1)),
|
||||||
|
((1, 0), List(0)),
|
||||||
|
((2, 1), List(1, 1)),
|
||||||
|
((3, 1), List(1, 1, 1)),
|
||||||
|
).foreach:
|
||||||
|
case ((repititions, value), expected) =>
|
||||||
|
test(s"fillList returns [$expected]"):
|
||||||
|
assertEquals(Problem15.fillList(value, repititions), expected)
|
||||||
Reference in New Issue
Block a user