Created
May 28, 2016 11:42
-
-
Save joesan/203d8a33726c29caead08a01eea98537 to your computer and use it in GitHub Desktop.
String K-Reduction implemented in Scala
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
val input = "abccaaaba" // cccaaaba -> ccbaaba -> caaaba -> baaba -> caba -> bba -> bc -> a | |
val distinctChars = input.distinct.sorted.toList | |
@tailrec | |
def reduceString(acc: List[Char], seq: List[Char]): List[Char] = seq match { | |
case Nil => | |
if (acc.toSet.size == 1) acc | |
else reduceString(List.empty[Char], acc) | |
case x :: Nil => | |
reduceString(acc :+ x, List.empty[Char]) | |
case x :: xs => | |
if (x != xs.head) | |
reduceString( | |
acc, | |
distinctChars.diff( | |
Seq(x, xs.headOption.getOrElse(List.empty[Char])) | |
) ++ Option(xs.tail).getOrElse(List.empty[Char]) | |
) | |
else | |
reduceString(x :: acc, xs) | |
} | |
println(reduceString(List.empty[Char], input.toCharArray.toList)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Given a string consisting of a,b and c's, we can perform the following operation: Take any two adjacent distinct characters and replace it with the third character. For example, if 'a' and 'c' are adjacent, they can replaced with 'b'.
What is the smallest string which can result by applying this operation repeatedly