Skip to content

Instantly share code, notes, and snippets.

@joshuakfarrar
Last active March 2, 2022 20:08
Show Gist options
  • Save joshuakfarrar/4564897951287fa3c3bfd768f3fe8b16 to your computer and use it in GitHub Desktop.
Save joshuakfarrar/4564897951287fa3c3bfd768f3fe8b16 to your computer and use it in GitHub Desktop.
another code golf-type interview question
// compress a string by counting its repeating characters
def compress(a: String): String = a.foldLeft("") { (acc, l) =>
acc.lastOption match {
case Some(c) =>
if (c == l) => {
acc.slice(acc.lastIndexOf(l) - 1, acc.lastIndexOf(l)).headOption match {
case Some(d) => c match {
case l => if (Character.isDigit(d)) {
s"${acc.slice(0, acc.lastIndexOf(l) - 1)}${Character.digit(d, 10) + 1}" :+ l // add 1 to repeating characters we have seen
} else {
s"${acc.slice(0, acc.lastIndexOf(l))}2" :+ l // initialize a character counter at 2 for an unseen repeating character
}
}
case None => s"2${l}" // rare case: the first character of the input string repeats
}
} else acc :+ l // the last character of the accumulator is not equal to the current character, append it
case None => l.toString // empty accumulator, we're just getting started!
}
}
val result = compress("ttestttiiiinggggg") == "2tes3t4in5g"
println(s"${result}") // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment