Skip to content

Instantly share code, notes, and snippets.

@sungkmi
Created March 20, 2015 13:24
Show Gist options
  • Save sungkmi/c760f073fa030f344c3c to your computer and use it in GitHub Desktop.
Save sungkmi/c760f073fa030f344c3c to your computer and use it in GitHub Desktop.
object Consonants extends App {
def nValue(s: String, n: Int): Long = ((0, 0, 0L) /: (0 until s.size)) {
case ((lastCount, last, acc), i) =>
val count = if ("aeiou" contains s(i)) 0 else lastCount + 1
val (nextLast, nextAcc) =
if (count >= n) (i - n + 2, acc + (i - n - last + 2) * (s.size - i)) else (last, acc)
(count, nextLast, nextAcc)
}._3
def process(lineIn: Iterator[String])(lineOut: String => Unit) =
for (i <- 1 to lineIn.next().toInt) {
val Array(s, n) = lineIn.next() split ' '
lineOut(s"Case #$i: ${nValue(s, n.toInt)}")
}
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 Consonants._
class ConsonantsTest extends FunSuite {
test("sample #1") {
assert(nValue("quartz", 3) === 4)
}
test("sample #2") {
assert(nValue("straight", 3) === 11)
}
test("sample #3") {
assert(nValue("gcj", 2) === 3)
}
test("sample #4") {
assert(nValue("tsetse", 2) === 11)
}
test("sample case") {
val input = """4
quartz 3
straight 3
gcj 2
tsetse 2""".lines
val expected = """Case #1: 4
Case #2: 11
Case #3: 3
Case #4: 11""".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.ref").getLines()
lineComparison(input, expected)
}
ignore("full large case") {
val input = io.Source.fromFile("A-large-practice.in").getLines()
val expected = io.Source.fromFile("A-large-practice.out.ref").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