Skip to content

Instantly share code, notes, and snippets.

@waynejo
Created June 13, 2014 14:19
Show Gist options
  • Save waynejo/aeff2c9eeeebc294fb09 to your computer and use it in GitHub Desktop.
Save waynejo/aeff2c9eeeebc294fb09 to your computer and use it in GitHub Desktop.
The Repeater
import scala.io.Source
import scala.annotation.tailrec
object Main {
def solve(input: List[String]): Option[Int] = {
case class TextAndCounts(text: String, counts: List[Int])
def countAndSimplify(text: String) = {
text.foldLeft(TextAndCounts("", List()))((acc, x) =>
if (0 < acc.text.length && acc.text.last == x)
acc.copy(counts = acc.counts.init :+ (acc.counts.last + 1))
else
TextAndCounts(acc.text + x, acc.counts :+ 1))
}
if (1 < input.map(countAndSimplify).map(_.text).toSet.size) {
None
} else {
val charCounts = input.map(countAndSimplify).map(_.counts)
val charCountsByCol = (0 until charCounts(0).length) map (i => charCounts.map(x => x(i)))
val medians = charCountsByCol.map(_.sorted).map(x => x(x.length / 2))
val differences = (0 until charCountsByCol.length) map (i => charCountsByCol(i).map(x => Math.abs(x - medians(i))))
Some(differences.map(_.sum).sum)
}
}
def main(args: Array[String]) {
val lines = Source.fromFile("A-large-practice.in").getLines()
val caseNum = lines.next().toInt
1 to caseNum foreach { caseIndex =>
{
val loopSize = lines.next().toInt
val inputs = for (i <- 0 until loopSize) yield lines.next()
val result = solve(inputs.toList) match {
case None => "Fegla Won"
case Some(x) => x
}
println(s"Case #$caseIndex: $result")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment