Skip to content

Instantly share code, notes, and snippets.

@sungkmi
Created March 6, 2015 13:07
Show Gist options
  • Save sungkmi/2a76a39fef74e8603f06 to your computer and use it in GitHub Desktop.
Save sungkmi/2a76a39fef74e8603f06 to your computer and use it in GitHub Desktop.
object CrazyRows extends App {
def minSwap(matrix: IndexedSeq[String]): Int =
((matrix map (_ lastIndexOf '1'), 0) /: (0 until matrix.size)) {
case ((rows, acc), limit) =>
val target = rows indexWhere { _ <= limit }
val (front, end) = rows splitAt target
(front ++ end.tail, acc + target)
}._2
def process(lineIn: Iterator[String])(lineOut: String => Unit) =
for (i <- 1 to lineIn.next().toInt) {
val n = lineIn.next().toInt
val matrix = IndexedSeq.fill(n) { lineIn.next() }
lineOut(s"Case #$i: ${minSwap(matrix)}")
}
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 CrazyRows._
class CrazyRowsTest extends FunSuite {
test("sample #1") {
val matrix = Vector("10", "11")
assert(minSwap(matrix) === 0)
}
test("sample #2") {
val matrix = Vector("001", "100", "010")
assert(minSwap(matrix) === 2)
}
test("sample #3") {
val matrix = Vector("1110", "1100", "1100", "1000")
assert(minSwap(matrix) === 4)
}
test("sample case") {
val input = """3
2
10
11
3
001
100
010
4
1110
1100
1100
1000""".lines
val expected = """Case #1: 0
Case #2: 2
Case #3: 4""".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)
}
test("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