Skip to content

Instantly share code, notes, and snippets.

@sungkmi
Created August 21, 2015 12:50
Show Gist options
  • Save sungkmi/1e85a9e6a26932281cf9 to your computer and use it in GitHub Desktop.
Save sungkmi/1e85a9e6a26932281cf9 to your computer and use it in GitHub Desktop.
object ReverseWords extends App {
def reverse(line: String): String = line.split(' ').reverse mkString " "
def reverse2(line: String): String = {
def reverse(ss: List[String]): String = ss match {
case Nil => ""
case x :: Nil => x
case x :: xs => reverse(xs) + " " + x
}
reverse((line split ' ').toList)
}
def reverse3(line: String): String = {
def reverseList(ss: List[String], acc: List[String] = Nil): List[String] = ss match {
case Nil => acc
case x :: xs => reverseList(xs, x :: acc)
}
reverseList(line.split(' ').toList) mkString " "
}
def reverse4(line: String): String =
(List.empty[String] /: line.split(' '))((acc, s) => s :: acc) mkString " "
def process(lineIn: Iterator[String])(lineOut: String => Unit) =
for (i <- 1 to lineIn.next().toInt) {
lineOut(s"Case #$i: ${reverse(lineIn.next())}")
}
val filename = "B-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 ReverseWords._
class SmoothingWindowTest extends FunSuite {
test("sample #1") {
assert(reverse("this is a test") === "test a is this")
}
test("sample case") {
val input = """3
this is a test
foobar
all your base""".lines
val expected = """Case #1: test a is this
Case #2: foobar
Case #3: base your all""".lines
lineComparison(input, expected)
}
test("full small case") {
val input = io.Source.fromFile("B-small-practice.in").getLines()
val expected = io.Source.fromFile("B-small-practice.out").getLines()
lineComparison(input, expected)
}
test("full large case") {
val input = io.Source.fromFile("B-large-practice.in").getLines()
val expected = io.Source.fromFile("B-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