Last active
November 10, 2015 21:26
-
-
Save salex89/300f75022b56c478de54 to your computer and use it in GitHub Desktop.
Chuck Norris puzzle solution in Scala from CodinGame.com
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
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