Skip to content

Instantly share code, notes, and snippets.

@salex89
Last active November 10, 2015 21:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save salex89/300f75022b56c478de54 to your computer and use it in GitHub Desktop.
Save salex89/300f75022b56c478de54 to your computer and use it in GitHub Desktop.
Chuck Norris puzzle solution in Scala from CodinGame.com
import math._
import scala.util._
object Solution extends App {
def spanAndEncode(message : String) : String =
{
val (same, rest) = message.span(_ == message.head)
val output = new StringBuilder
output ++= ("0" * (2 - same.head.asDigit)) + " " + ("0" * same.length)
if(rest.nonEmpty)
{
output ++= " "
output ++= spanAndEncode(rest)
}
output.toString()
}
val message = readLine
//padding to 7 bytes is important, toBinaryString truncates the leading 0's
val binaryCodedMessage = message.flatMap(char => char.toInt.toBinaryString.reverse.padTo(7,'0').reverse)
val result = spanAndEncode(binaryCodedMessage)
println(result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment