Skip to content

Instantly share code, notes, and snippets.

@sungkmi
Last active August 29, 2015 14:03
Show Gist options
  • Save sungkmi/09b768627c256fe6c3c3 to your computer and use it in GitHub Desktop.
Save sungkmi/09b768627c256fe6c3c3 to your computer and use it in GitHub Desktop.
object ReadPhoneNumber extends App {
def read(numberStr: String, formatStr: String): String = {
val (numbers, format) = (numberStr map (_ - '0'), formatStr split '-' map (_.toInt))
val segments: Seq[Seq[Int]] = ((List.empty[Seq[Int]], numbers) /: format) {
case ((acc, numbers), count) => val (h, t) = numbers splitAt count; (h :: acc, t)
}._1.reverse
def runLength: Seq[Int] => Seq[(Int, Int)] = _.foldRight(List.empty[(Int, Int)]) {
case (digit, (d, r) :: accTail) if digit == d => (d, r + 1) :: accTail
case (digit, acc) => (digit, 1) :: acc
}
segments flatMap runLength flatMap {
case (d, r) =>
val digitStr = ("zero one two three four five six seven eight nine" split ' ')(d)
if (2 <= r && r <= 10)
Seq(("double triple quadruple quintuple sextuple septuple octuple nonuple decuple"
split ' ')(r - 2), digitStr)
else
Seq.fill(r)(digitStr)
} mkString " "
}
def process(lineIn: Iterator[String])(lineOut: String => Unit) =
for (i <- 1 to lineIn.next().toInt) {
val Array(n, f) = lineIn.next() split ' '
lineOut(s"Case #$i: ${read(n, f)}")
}
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