Skip to content

Instantly share code, notes, and snippets.

@sungkmi
Last active August 29, 2015 14:14
Show Gist options
  • Save sungkmi/e5c9ac97fc315c99d0c4 to your computer and use it in GitHub Desktop.
Save sungkmi/e5c9ac97fc315c99d0c4 to your computer and use it in GitHub Desktop.
object TextMessageOutrage extends App {
def minNumberOfKeyPressed(numberOfKey: Int, letterFrequencies: Seq[Int]): Long = {
for {
(freqs, index) <- (letterFrequencies sortWith (_ > _) grouped numberOfKey).zipWithIndex
freq <- freqs
} yield freq.toLong * (index + 1)
}.sum
def process(lineIn: Iterator[String])(lineOut: String => Unit) =
for (i <- 1 to lineIn.next().toInt) {
def readInts() = lineIn.next() split ' ' map (_.toInt)
val Array(p, k, l) = readInts()
val letterFrequencies = readInts()
lineOut(s"Case #$i: ${minNumberOfKeyPressed(k, letterFrequencies)}")
}
val writer = new java.io.PrintWriter("a.large.out")
try {
process(io.Source.fromFile("A-large-practice.in").getLines) { s =>
writer.println(s)
writer.flush()
}
} finally {
writer.flush(); writer.close()
}
}
import org.scalatest._
import TextMessageOutrage._
class TextMessageOutrageTest extends FunSuite {
test("sample #1") {
assert(minNumberOfKeyPressed(2, Seq(8, 2, 5, 2, 4, 9)) === 47)
}
test("sample #2") {
assert(minNumberOfKeyPressed(9, Seq(1, 1, 1, 100, 100, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 10, 11, 11, 11, 11, 1, 1, 1, 100)) === 397)
}
test("sample case") {
val input = """2
3 2 6
8 2 5 2 4 9
3 9 26
1 1 1 100 100 1 1 1 1 1 1 1 1 1 1 1 1 10 11 11 11 11 1 1 1 100""".lines
val expected = """Case #1: 47
Case #2: 397""".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.out.ref").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.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