Skip to content

Instantly share code, notes, and snippets.

@joesan
Created May 28, 2016 11:42
Show Gist options
  • Save joesan/203d8a33726c29caead08a01eea98537 to your computer and use it in GitHub Desktop.
Save joesan/203d8a33726c29caead08a01eea98537 to your computer and use it in GitHub Desktop.
String K-Reduction implemented in Scala
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))
@joesan
Copy link
Author

joesan commented May 28, 2016

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment