Last active
August 29, 2015 14:03
-
-
Save sungkmi/09b768627c256fe6c3c3 to your computer and use it in GitHub Desktop.
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
object ReadPhoneNumber extends App { | |
def read(number: String, format: List[Int]): String = convert { | |
formatting(number, format) flatMap runLength | |
} | |
def convert(runLength: List[(Int, Int)]): String = { | |
val NUMBER_TO_STRING = "zero one two three four five six seven eight nine" split ' ' | |
val COUNT_STRING = "double triple quadruple quintuple sextuple septuple octuple nonuple decuple" split ' ' | |
runLength.map { | |
case (n, r) if r > 10 => List.fill(r)(NUMBER_TO_STRING(n)) mkString " " | |
case (n, r) if r > 1 => COUNT_STRING(r - 2) + " " + NUMBER_TO_STRING(n) | |
case (n, r) => NUMBER_TO_STRING(n) | |
} mkString " " | |
} | |
def formatting(number: String, format: List[Int]): List[List[Int]] = ((List.empty[String], number) /: format) { | |
case ((acc, number), count) => ((number take count) :: acc, number drop count) | |
}._1.reverse.map(_.map(_ - '0').toList) | |
def runLength(number: List[Int]): List[(Int, Int)] = (List.empty[(Int, Int)] /: number) { | |
case ((n, r) :: xs, digit) if n == digit => (n, r + 1) :: xs | |
case (acc, digit) => (digit, 1) :: acc | |
}.reverse | |
def process(iter: Iterator[String])(lineOut: String => Unit) = for (i <- 1 to iter.next().toInt) { | |
val Array(n, f) = iter.next() split ' ' | |
lineOut(s"Case #$i: ${read(n, (f split '-').map(_.toInt).toList)}") | |
} | |
val writer = new java.io.PrintWriter("a.out") | |
try { | |
process(io.Source.fromFile("A-large-practice.in").getLines)(writer.println) | |
} finally { | |
writer.flush(); writer.close() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment