Skip to content

Instantly share code, notes, and snippets.

@sungkmi
Created January 6, 2015 15:20
Show Gist options
  • Save sungkmi/c2da3893f0d576d952ba to your computer and use it in GitHub Desktop.
Save sungkmi/c2da3893f0d576d952ba to your computer and use it in GitHub Desktop.
object DataPacking extends App {
def minDisc(capacity: Int, files: Seq[Int]): Int = {
@annotation.tailrec
def loop(sorted: Vector[Int], count: Int): Int =
if (sorted.size <= 1) sorted.size + count
else {
val (front, end) = sorted.init.span(_ <= capacity - sorted.last)
loop(if (front.isEmpty) end else front.init ++ end, count + 1)
}
loop(files.sorted.toVector, 0)
}
def process(lineIn: Iterator[String])(lineOut: String => Unit) =
for (i <- 1 to lineIn.next().toInt) {
def readInts() = lineIn.next() split ' ' map (_.toInt)
val Array(n, x) = readInts()
lineOut(s"Case #$i: ${minDisc(x, readInts())}")
}
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 DataPacking._
class DataPackingTest extends FunSuite {
test("sample #1") {
assert(minDisc(100, Seq(10, 20, 70)) === 2)
}
test("sample #2") {
assert(minDisc(100, Seq(30, 40, 60, 70)) === 2)
}
test("sample #3") {
assert(minDisc(100, Seq(10, 20, 30, 40, 60)) === 3)
}
test("sample case") {
val input = """3
3 100
10 20 70
4 100
30 40 60 70
5 100
10 20 30 40 60""".lines
val expected = """Case #1: 2
Case #2: 2
Case #3: 3""".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