salex89
11/9/2015 - 10:35 PM

Chuck Norris puzzle solution in Scala from CodinGame.com

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)
}