Skip to content

Instantly share code, notes, and snippets.

@krikit
Last active August 29, 2015 14:13
Show Gist options
  • Save krikit/7ad10dcd00d57cc1a0f3 to your computer and use it in GitHub Desktop.
Save krikit/7ad10dcd00d57cc1a0f3 to your computer and use it in GitHub Desktop.
object Rotate extends App {
def pushRight(line: String): String = {
// gravity from right side
// same as rotate clock wise and gravity from bottom
val N = line.size
val dotRemoved = line.replace(".", "")
val dots = "." * (N - dotRemoved.size)
dots + dotRemoved
}
def getWinners(line: String, K: Int): Set[Char] = {
// get winner character from a line
val kLengthSublines = line.sliding(K)
val winnerChars = kLengthSublines.map(_.toSet).filter(_.size == 1)
winnerChars.flatten.filter(_ != '.').toSet
}
def makeCols(lines: List[String]): List[String] = {
// make list of column(vertical) lines
val N = lines(0).size
(for (i <- 0 until N) yield lines.map(_(i)).mkString).toList
}
def makeDiags(lines: List[String]): List[String] = {
// make list of diagonal lines
// ABC ..ABC.. ==> topLeftToBottomRight: ..G .DH AEI BF. C..
// DEF ==> ..DEF..
// GHI ..GHI.. ==> topRightToBottomLeft: ..I .FH CEG BD. A..
val N = lines(0).size
val dotWrappedLines = lines.map ("." * (N - 1) + _ + "." * (N - 1))
val topLeftToBottomRight = for (i <- 0 until 2 * N - 1) yield {
(for (j <- 0 until N) yield dotWrappedLines(j)(i + j)).mkString
}
val topRightToBottomLeft = for (i <- 3 * N - 3 to N - 1 by -1) yield {
(for (j <- 0 until N) yield dotWrappedLines(j)(i - j)).mkString
}
(topLeftToBottomRight ++ topRightToBottomLeft).toList
}
def solve(lines: List[String], K: Int): String = {
val pushedLines = lines map pushRight
val pushedCols = makeCols(pushedLines)
val pushedDiags = makeDiags(pushedLines)
val all = pushedLines ++ pushedCols ++ pushedDiags
val winners = all.map(getWinners(_, K)).flatten.toSet
winners.toList match {
case Nil => "Neither"
case 'B' :: Nil => "Blue"
case 'R' :: Nil => "Red"
case _ => "Both"
}
}
//////////
// main //
//////////
if (args.length > 0) Console.setIn(new java.io.FileInputStream(args(0)))
if (args.length > 1) Console.setOut(new java.io.FileOutputStream(args(1)))
for (t <- 1 to readInt) {
val Array(n, k) = readLine.split(" ").map(_.toInt)
val lines = (for (r <- 1 to n) yield readLine).toList
println(s"Case #${t}: ${solve(lines, k)}")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment