-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: Andreas Roehler <andreas.roehler@online.de>
- Loading branch information
1 parent
ca32f98
commit 2d34783
Showing
1 changed file
with
31 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |