Created
April 10, 2015 13:02
-
-
Save sungkmi/b89a6aee3e2e69560493 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object UpAndDown extends App { | |
@annotation.tailrec | |
def minSwap(ints: IndexedSeq[Int], count: Int = 0): Int = | |
if (ints.isEmpty) count | |
else { | |
val minIndex = ints.zipWithIndex.min._2 | |
val (left, right) = ints splitAt minIndex | |
minSwap(left ++ right.tail, count + (left.size min right.tail.size)) | |
} | |
def process(lineIn: Iterator[String])(lineOut: String => Unit) = | |
for (i <- 1 to lineIn.next().toInt) { | |
val n = lineIn.next().toInt | |
val ints = lineIn.next().split(' ').map(_.toInt) | |
lineOut(s"Case #$i: ${minSwap(ints)}") | |
} | |
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() | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.scalatest._ | |
import UpAndDown._ | |
class UpAndDownTest extends FunSuite { | |
test("sample #1") { | |
assert(minSwap(Vector(1,2,3)) === 0) | |
} | |
test("sample #2") { | |
assert(minSwap(Vector(1,8,10,3,7)) === 1) | |
} | |
test("sample case") { | |
val input = """2 | |
3 | |
1 2 3 | |
5 | |
1 8 10 3 7""".lines | |
val expected = """Case #1: 0 | |
Case #2: 1""".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