Created
June 15, 2018 06:46
-
-
Save mikekwright/b3ee383bbcd17f4407951e5662a3a6f7 to your computer and use it in GitHub Desktop.
Solution for chuck_norris problem from codingame in scala.
This file contains hidden or 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
| // https://www.codingame.com/training/easy/chuck-norris | |
| import math._ | |
| import scala.util._ | |
| /** | |
| * Auto-generated code below aims at helping you parse | |
| * the standard input according to the problem statement. | |
| **/ | |
| object Solution extends App { | |
| val message = readLine | |
| val messageBinary = message.map(x => BigInt(x).toString(2).reverse.padTo(7, "0").reverse.mkString("")).mkString("") | |
| def binaryCounter(num: Char, restMessage: String): (Char, Int, String) = { | |
| if (restMessage == null || !restMessage.nonEmpty) { | |
| (num, 0, null) | |
| } else if (restMessage.head == num) { | |
| val t: (Char, Int, String) = binaryCounter(num, restMessage.tail) | |
| (t._1, t._2 + 1, t._3) | |
| } else { | |
| (num, 0, restMessage) | |
| } | |
| } | |
| def getGroupings(message: String): List[(Char, Int)] = { | |
| if (message == null) { | |
| List() | |
| } else { | |
| val t: (Char, Int, String) = binaryCounter(message.head, message) | |
| (t._1, t._2) :: getGroupings(t._3) | |
| } | |
| } | |
| def encodeGroup(group: (Char, Int)) = { | |
| val (num, count) = group | |
| val header = if (num == '0') { | |
| "00" | |
| } else { | |
| "0" | |
| } | |
| val code = (1 to count).map(_ => "0").mkString("") | |
| header + " " + code | |
| } | |
| println(getGroupings(messageBinary).map(encodeGroup).mkString(" ")) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment