Skip to content

Commit

Permalink
solution2.5.2.12.scala provided
Browse files Browse the repository at this point in the history
Signed-off-by: Andreas Roehler <andreas.roehler@online.de>
  • Loading branch information
andreas-roehler committed Dec 15, 2024
1 parent ca32f98 commit 2d34783
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions chapter02/worksheets/solution2.5.2.12.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
Exercise 2.5.2.12
Transform a sequence by removing adjacent repeated elements when
they are repeated more than 𝑘 times. Repetitions up to 𝑘 times
should remain unchanged.
The required type signature and a sample test:
def removeDups[A](s: Seq[A], k: Int): Seq[A] = ???
scala> removeDups(Seq(1, 1, 1, 1, 5, 2, 2, 5, 5, 5, 5, 5, 1), 3)
res0: Seq[Int] = List(1, 1, 1, 5, 2, 2, 5, 5, 5, 1)
*/

def removeDupsIntern[A](xs: Seq[A], k: Int, res: Seq[A] = Seq.empty): Seq[A] = {
if (xs.isEmpty) res.reverse
else {
val a: Seq[A] = xs.takeWhile(_ == xs.head).take(k)
val b = xs.dropWhile(_ == xs.head)
removeDupsIntern(b, k, a ++ res)
}
}

def removeDups[A](s: Seq[A], k: Int): Seq[A] = {
removeDupsIntern(s, k)
}

val result = removeDups(Seq(1, 1, 1, 1, 5, 2, 2, 5, 5, 5, 5, 5, 1), 3)
val expected: Seq[Int] = List(1, 1, 1, 5, 2, 2, 5, 5, 5, 1)
assert(result == expected)

0 comments on commit 2d34783

Please sign in to comment.