Skip to content

Instantly share code, notes, and snippets.

@sungkmi
Created June 5, 2015 13:27
Show Gist options
  • Save sungkmi/e1f406b4e7848812e034 to your computer and use it in GitHub Desktop.
Save sungkmi/e1f406b4e7848812e034 to your computer and use it in GitHub Desktop.
object CounterCulture extends App {
def minCount(n: Long): Long = minCount(n.toString)
def minCount(n: String): Long =
if (n.toLong < 20) n.toLong
else {
val (front, back) = n splitAt (n.size + 1) / 2
val beforeReverse = "1" + "0" * (back.size - 1) + front.reverse
if (back.toLong == 0) minCount(n.toLong - 1) + 1
else {
val train9 = "9" * (n.size - 1)
minCount(train9) +
(beforeReverse.toLong - train9.toLong) +
(back.toLong - 1) +
(if (beforeReverse == beforeReverse.reverse) 0 else 1)
}
}
def process(lineIn: Iterator[String])(lineOut: String => Unit) =
for (i <- 1 to lineIn.next().toInt) {
lineOut(s"Case #$i: ${minCount(lineIn.next())}")
}
val filename = "A-large-practice"
val writer = new java.io.PrintWriter(filename + ".out")
try {
process(io.Source.fromFile(filename + ".in").getLines) { s =>
writer.println(s); writer.flush()
}
} finally {
writer.flush(); writer.close()
}
}
import org.scalatest._
import CounterCulture._
class CounterCultureTest extends FunSuite {
test("sample #1") {
assert(minCount(1) === 1)
}
test("sample #2") {
assert(minCount(19) === 19)
}
test("sample #3") {
assert(minCount(23) === 15)
}
test("21") {
assert(minCount(21) === 13)
}
test("123456") {
assert(minCount(123456) === minCount(99999) + (100321 - 99999) + (123456 - 123001) + 1)
}
test("3000") {
assert(minCount(3000) === (3000 - 2901) + (1092 - 999) + minCount("999") + 1)
}
test("sample case") {
val input = """3
1
19
23""".lines
val expected = """Case #1: 1
Case #2: 19
Case #3: 15""".lines
lineComparison(input, expected)
}
test("full small case") {
val input = io.Source.fromFile("A-small-practice.in").getLines()
val expected = io.Source.fromFile("A-small-practice.out").getLines()
lineComparison(input, expected)
}
test("full large case") {
val input = io.Source.fromFile("A-large-practice.in").getLines()
val expected = io.Source.fromFile("A-large-practice.out").getLines()
lineComparison(input, expected)
}
def lineComparison(input: Iterator[String], expected: Iterator[String]) {
process(input) { s =>
for (line <- s.lines) assert(line.trim === expected.next().trim)
}
assert(expected.hasNext === false, "Finished too fast.")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment