Skip to content

Instantly share code, notes, and snippets.

@swkimme
Created December 5, 2014 13:22
Show Gist options
  • Save swkimme/94396f430c094245bb89 to your computer and use it in GitHub Desktop.
Save swkimme/94396f430c094245bb89 to your computer and use it in GitHub Desktop.
welcome_to_code_jam.scala
val inputFilePath = "/Users/swkim/Documents/scala-study/src/main/resources/C-small-practice-welcome_to_code_jam.in"
val outputFilePath = "/Users/swkim/Documents/scala-study/src/main/resources/C-small-practice-welcome_to_code_jam.out"
import java.io.File
import scala.io.Source
val file = new File(inputFilePath)
val lines = Source.fromFile(file).getLines()
val inputs = lines.toList.drop(1)
val targetString = "welcome to code jam"
def getAnswer(testString: String) = {
def c(i: Int, j: Int): Int = {
if (i == -1) return 0
if (j == -1) return 1
if (testString(i) == targetString(j)) c(i-1, j) + c(i, j-1)
else c(i-1, j)
}
c(testString.length-1, targetString.length-1)
}
def format(x: (Int, Int)) = {
val result = x._1
val i = x._2 + 1
s"Case #$i: ${result.formatted("%04d")}"
}
val answer = inputs.map(getAnswer).zipWithIndex.map{format}
// save into output file
val outFile = new File(outputFilePath)
def printToFile(f: java.io.File)(op: java.io.PrintWriter => Unit) {
val p = new java.io.PrintWriter(f)
try { op(p) } finally { p.close() }
}
val data = answer.toArray
printToFile(outFile) { p =>
data.foreach(p.println)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment