Skip to content

Instantly share code, notes, and snippets.

@sungkmi
Created February 6, 2015 12:55
Show Gist options
  • Save sungkmi/b0bbe22bf530b50767b3 to your computer and use it in GitHub Desktop.
Save sungkmi/b0bbe22bf530b50767b3 to your computer and use it in GitHub Desktop.
object TheNextNumber extends App {
def nextNumber(number: String): String = {
@annotation.tailrec
def cutSuffix(number: String, acc: List[Char]): (String, List[Char]) =
if (number.isEmpty) ("0", acc)
else if (number.last < acc.head) (number, acc)
else cutSuffix(number.init, number.last :: acc)
val (front, back) = cutSuffix(number.init, number.last :: Nil)
val digit = back.filter(_ > front.last).min
front.init + digit ++ (front.last :: back diff digit :: Nil).sorted.mkString
}
def process(lineIn: Iterator[String])(lineOut: String => Unit) =
for (i <- 1 to lineIn.next().toInt) lineOut(s"Case #$i: ${nextNumber(lineIn.next())}")
val writer = new java.io.PrintWriter("b.large.out")
try {
process(io.Source.fromFile("B-large-practice.in").getLines) { s =>
writer.println(s)
writer.flush()
}
} finally {
writer.flush(); writer.close()
}
}
import org.scalatest._
import TheNextNumber._
class TheNextNumberTest extends FunSuite {
test("sample #1") {
assert(nextNumber("115") === "151" )
}
test("sample #2") {
assert(nextNumber("1051") === "1105" )
}
test("sample #3") {
assert(nextNumber("6233") === "6323" )
}
test("sample case") {
val input = """3
115
1051
6233""".lines
val expected = """Case #1: 151
Case #2: 1105
Case #3: 6323""".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.out.ref").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.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