Problem 09
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
package ninetyNineScalaProblems
|
||||
|
||||
import scala.annotation.tailrec
|
||||
|
||||
object Problem09:
|
||||
def sameValueRepeatedAnyTime(list: List[Any]): Boolean =
|
||||
@tailrec
|
||||
def loop(cursor: List[Any], acc: Boolean): Boolean =
|
||||
cursor match
|
||||
case List(x) =>
|
||||
true
|
||||
case x1 :: List(x2) if x1 == x2 =>
|
||||
true
|
||||
case x1 :: x2 :: tail if x1 == x2 =>
|
||||
loop(x1 :: tail, true)
|
||||
case x :: tail =>
|
||||
false
|
||||
case Nil =>
|
||||
true
|
||||
|
||||
loop(list, true)
|
||||
|
||||
def countRepititions(list: List[Any]): Int =
|
||||
@tailrec
|
||||
def loop(cursor: List[Any], acc: Int): Int =
|
||||
cursor match
|
||||
case e1 :: e2 :: Nil if e1 == e2 =>
|
||||
acc + 2
|
||||
case e1 :: e2 :: tail if e1 == e2 =>
|
||||
loop(e2 :: tail, acc + 1)
|
||||
case e :: tail =>
|
||||
acc + 1
|
||||
case Nil =>
|
||||
acc
|
||||
|
||||
loop(list, 0)
|
||||
|
||||
def nthElementToEnd(list: List[Any], n: Int): List[Any] =
|
||||
@tailrec
|
||||
def loop(cursor: List[Any], acc: List[Any], position: Int): List[Any] =
|
||||
cursor match
|
||||
case e :: tail if position >= n =>
|
||||
loop(tail, e :: acc, position + 1)
|
||||
case e :: tail =>
|
||||
loop(tail, acc, position + 1)
|
||||
case Nil =>
|
||||
acc
|
||||
|
||||
loop(list, List(), 0).reverse
|
||||
|
||||
def consecutiveDuplicatesIntoSublists(list: List[Any]): List[List[Any]] =
|
||||
@tailrec
|
||||
def loop(cursor: List[Any], acc: List[List[Any]]): List[List[Any]] =
|
||||
val repititions = countRepititions(cursor)
|
||||
cursor match
|
||||
case Nil =>
|
||||
acc
|
||||
case _ if repititions == 0 =>
|
||||
acc
|
||||
case _ => cursor match
|
||||
case e :: tail =>
|
||||
loop(nthElementToEnd(tail, repititions - 1), List.fill(repititions)(e) :: acc)
|
||||
case Nil =>
|
||||
acc
|
||||
|
||||
loop(list, List()).reverse
|
||||
Reference in New Issue
Block a user