Skip to content

Instantly share code, notes, and snippets.

@sungkmi
Last active August 29, 2015 14:02
Show Gist options
  • Save sungkmi/dc94fa84cf27b3b5082e to your computer and use it in GitHub Desktop.
Save sungkmi/dc94fa84cf27b3b5082e to your computer and use it in GitHub Desktop.
object ChargingChaos extends App {
def minMove(inputs: Seq[String]): Option[Int] = {
def runLength(s: String) = (List.empty[(Char, Int)] /: s) {
case ((c, n) :: tail, char) if c == char =>
(c, n + 1) :: tail
case (acc, char) =>
(char, 1) :: acc
}.reverse.unzip
val (chars, lengths) = (inputs map runLength).unzip
if (chars.toSet.size > 1) None
else Some {
(List.fill(lengths.head.size)(List.empty[Int]) /: lengths) {
_ zip _ map { case (acc, x) => x :: acc }
}.map { acc =>
val diff = acc.toVector.sorted
val median = diff(diff.size / 2)
diff.map(math abs _ - median).sum
}.sum
}
}
def process(iter: Iterator[String])(out: String => Unit) =
for (i <- 1 to iter.next().toInt) {
val n = iter.next().toInt
val input = Seq.fill(n)(iter.next())
out(s"Case #$i: ${minMove(input) getOrElse "Fegla Won"}")
}
import java.io._
val out = new PrintStream(new File("a.out"))
try {
process(io.Source.fromFile("A-large-practice.in").getLines) { s: String =>
out.println(s)
}
} finally {
out.flush; out.close
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment