I am working on an exercise that I need to figure out how to add designated marker char between two duplicate elements in a list.
input - a string
output - a list of string pairs
Two rules;
- if the input string has duplicate characters, a char
xneeds to be added between them. For ex;treeswill becometr, ex, es - if the duplicate char pair is
xx, add aqbetween them. For ex;boxxbecomesbo,xq, x
Both rules run together on the input, For example;
if the input is HelloScalaxxxx the output should be List("He", "lx", "lo", "Sc", "al", "ax", "xq", "xq", "x")
I got the first rule working with following code and struggling to get the second rule satisfied.
input.foldRight[List[Char]](Nil) {
case (h, t) =>
println(h :: t)
if (t.nonEmpty) {
(h, t.head) match {
case ('x', 'x') => t ::: List(h, 'q')
case _ => if (h == t.head) h :: 'x' :: t else h :: t
}
} else h :: t
}
.mkString("").grouped(2).toSeq
I think I am close, for the input HelloScalaxxxx it produces List("He", "lx", "lo", "Sc", "al", "ax", "xq", "xq", "xq"), but with an extra q in the last pair.
I don't want to use a regex-based solution. Looking for an idiomatic Scala version.
I tried searching for existing answers but no luck. Any help would be appreciated. Thank you.