Skip to content

Instantly share code, notes, and snippets.

@sungkmi
Created September 25, 2015 12:05
Show Gist options
  • Save sungkmi/5859e300ea7ff7410f41 to your computer and use it in GitHub Desktop.
Save sungkmi/5859e300ea7ff7410f41 to your computer and use it in GitHub Desktop.
object Googlander extends App {
lazy val memo = collection.mutable.Map.empty[(Int, Int), Long]
def countPaths(r: Int)(c: Int): Long = memo.getOrElseUpdate(
(r, c),
if (c <= 1) 1 else (1 to r map countPaths(c - 1)).sum
)
def process(lineIn: Iterator[String])(lineOut: String => Unit) =
for (i <- 1 to lineIn.next().toInt) {
val Array(r, c) = lineIn.next().split(' ').map(_.toInt)
lineOut(s"Case #$i: ${countPaths(r)(c)}")
}
val filename = "D-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 Googlander._
class GooglanderTest extends FunSuite {
test("sample #1") {
assert(countPaths(1)(1) === 1)
}
test("sample #2") {
assert(countPaths(1)(3) === 1)
}
test("sample #3") {
assert(countPaths(3)(3) === 6)
}
test("2 x 3") {
assert(countPaths(2)(3) === countPaths(2)(1) + countPaths(2)(2))
}
test("sample case") {
val input = """3
1 1
1 3
3 3""".lines
val expected = """Case #1: 1
Case #2: 1
Case #3: 6""".lines
lineComparison(input, expected)
}
test("full small case") {
val input = io.Source.fromFile("D-small-practice.in").getLines()
val expected = io.Source.fromFile("D-small-practice.out").getLines()
lineComparison(input, expected)
}
test("full large case") {
val input = io.Source.fromFile("D-large-practice.in").getLines()
val expected = io.Source.fromFile("D-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