Skip to content

Instantly share code, notes, and snippets.

@theodoreLee
Created August 28, 2015 13:28
Show Gist options
  • Save theodoreLee/17c1fda61277806342cb to your computer and use it in GitHub Desktop.
Save theodoreLee/17c1fda61277806342cb to your computer and use it in GitHub Desktop.
import java.io.FileOutputStream
import scala.io.Source
object LogSet {
def solve(seq:Seq[String]) = {
val sPrime = seq.head.split(' ').map(_.toLong).reverse
val frequencies = seq(1).split(' ').map(_.toLong).reverse
val stream:Stream[Long] = {
def loop(sP:List[Long], fre:List[Long]):Stream[Long] = fre match {
case Nil => Stream.empty
case x :: xs if x > 0 => sP.head #:: loop(sP, (x-1)::xs)
case x :: xs => loop(sP.tail, xs)
}
loop(sPrime.toList, frequencies.toList)
}
def _solve(xs:Stream[Long], cnt:Int, accr:List[Long]):List[Long] = xs match {
case Stream() => accr
case _ if xs.tail.isEmpty => accr
case _ =>
val large = xs.head
val newXs = xs.drop(cnt)
val small = newXs.head
_solve(newXs, cnt * 2, (large - small) :: accr)
}
def _solve2(xs:List[Long],accr:Long, acc:List[Long]):List[Long] = xs match {
case _ if accr == sPrime.head => (xs ++ acc).sorted
case x :: xs => _solve2(xs, accr - x, -x :: acc)
}
val ret = _solve(stream, 1, Nil)
_solve2(ret, ret.sum, Nil).mkString(" ")
}
def main(args: Array[String]): Unit = {
val INPUT = "test.in"
val OUTPUT = INPUT.takeWhile(_ != '.') + ".out"
val isConsole = true
val itr = Source.fromFile(INPUT).getLines()
val stream = if (isConsole) Console.out else new FileOutputStream(OUTPUT)
try {
Console.withOut(stream) {
val sets = itr.next().toInt
(1 to sets).foreach { set =>
itr.next()
val seq = Seq(itr.next(),itr.next())
println(f"Case #$set: ${solve(seq)}")
}
}
} finally {
stream.flush()
if (!isConsole) stream.close()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment