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))
|
||||
Reference in New Issue
Block a user