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] = {
val (chars, lengths) = inputs.map(runLength(_).unzip).unzip
if ((Set.empty[List[Char]] /: chars)(_ + _).size > 1) None
else Some {
val diffs = (List.fill(lengths.head.size)(List.empty[Int]) /: lengths) {
(acc, v) =>
(acc zip v).map {
case (acc, x) => x :: acc
}
} map (_.toVector.sorted)
(for (diff <- diffs) yield {
val median = diff(diff.size / 2)
(for {
x <- diff
} yield math.abs(x - median)).sum
}).sum
}
}
def runLength(s: String): List[(Char, Int)] = {
(((s.head, 1) :: Nil) /: s.tail) {
case ((c, n) :: tail, char) if c == char =>
(c, n + 1) :: tail
case (acc, char) =>
(char, 1) :: acc
}
}.reverse
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