Skip to content

Instantly share code, notes, and snippets.

@mikekwright
Created June 15, 2018 06:46
Show Gist options
  • Select an option

  • Save mikekwright/b3ee383bbcd17f4407951e5662a3a6f7 to your computer and use it in GitHub Desktop.

Select an option

Save mikekwright/b3ee383bbcd17f4407951e5662a3a6f7 to your computer and use it in GitHub Desktop.
Solution for chuck_norris problem from codingame in scala.
// 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