Skip to content

Instantly share code, notes, and snippets.

@sungkmi
Created July 25, 2014 12:59
Show Gist options
  • Save sungkmi/4ab8a7a93a570cdff0ff to your computer and use it in GitHub Desktop.
Save sungkmi/4ab8a7a93a570cdff0ff to your computer and use it in GitHub Desktop.
object Sorting extends App {
def sort(s: Int*): Seq[Int] = {
val odds = s.filter(_ % 2 != 0).toList
val even = s.filter(_ % 2 == 0).toList
val mask = s.map(_ % 2 != 0).toList
merge(odds.sorted, even.sorted.reverse, mask)
}
@annotation.tailrec
def merge(odds: List[Int], even: List[Int], mask: List[Boolean], acc: List[Int] = Nil): List[Int] =
if (mask.isEmpty) acc.reverse
else {
val (odds0, even0, current) =
if (mask.head) (odds.tail, even, odds.head) else (odds, even.tail, even.head)
merge(odds0, even0, mask.tail, current :: acc)
}
def process(lineIn: Iterator[String])(lineOut: String => Unit) =
for (i <- 1 to lineIn.next().toInt) {
val n = lineIn.next()
val ss = lineIn.next().split(' ').map(_.toInt)
lineOut(s"Case #$i: ${sort(ss: _*) mkString " "}")
}
val writer = new java.io.PrintWriter("c.large.out")
try {
process(io.Source.fromFile("C-large-practice.in").getLines)(writer.println)
} finally {
writer.flush(); writer.close()
}
}
import org.scalatest._
import Sorting._
class SortingTest extends FunSuite {
test("sample #1") {
assert(sort(5, 2, 4, 3, 1) === Seq(1, 4, 2, 3, 5))
}
test("sample #2") {
assert(sort(-5,-12, 87, 2, 88, 20, 11) === Seq(-5, 88, 11, 20, 2, -12, 87))
}
test("sample case") {
val input = """2
5
5 2 4 3 1
7
-5 -12 87 2 88 20 11""".lines
val expected = """Case #1: 1 4 2 3 5
Case #2: -5 88 11 20 2 -12 87""".lines
process(input) { s =>
assert(s === expected.next())
}
}
test("full small case") {
val input = io.Source.fromFile("C-small-practice.in").getLines()
val expected = io.Source.fromFile("c.small.out.ref").getLines()
process(input) { s =>
assert(s === expected.next())
}
}
test("full large case") {
val input = io.Source.fromFile("C-large-practice.in").getLines()
val expected = io.Source.fromFile("c.large.out.ref").getLines()
process(input) { s =>
assert(s === expected.next())
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment