Skip to content

Instantly share code, notes, and snippets.

@sungkmi
Last active August 29, 2015 14:09
Show Gist options
  • Save sungkmi/f93cfba579f747f0cc76 to your computer and use it in GitHub Desktop.
Save sungkmi/f93cfba579f747f0cc76 to your computer and use it in GitHub Desktop.
object SquareTiles extends App {
def cover(tiles: List[String]): Option[List[String]] = {
if (tiles.forall(!_.contains('#'))) Some(tiles)
else step(tiles) match {
case None => None
case Some(next) => cover(next)
}
}
def step(tiles: List[String]): Option[List[String]] = {
val (pre, body) = tiles.span(!_.contains('#'))
if (body.size < 2) None
else {
val (x :: y :: xs, tail) = body splitAt 2
val (left, middle) = (x zip y).span(_._1 != '#')
if (middle startsWith Seq(('#', '#'), ('#', '#')))
Some {
val (l1, l2) = (left ++ Vector(('/', '\\'), ('\\', '/')) ++ middle.drop(2)).unzip
pre ::: l1.mkString :: l2.mkString :: tail
}
else None
}
}
def process(lineIn: Iterator[String])(lineOut: String => Unit) =
for (i <- 1 to lineIn.next().toInt) {
val Array(r, c) = lineIn.next().split(' ').map(_.toInt)
val tiles = List.fill(r)(lineIn.next())
lineOut(s"Case #$i:")
cover(tiles) match {
case None => lineOut("Impossible")
case Some(lines) => lines.foreach(lineOut)
}
}
val writer = new java.io.PrintWriter("a.large.out")
try {
process(io.Source.fromFile("A-large-practice.in").getLines)(writer.println)
} finally {
writer.flush(); writer.close()
}
}
import org.scalatest._
import SquareTiles._
class SquareTilesTest extends FunSuite {
test("sample #1") {
assert(cover(List("###","###")) === None)
}
test("sample #2") {
assert(cover(List(".")) === Some(List(".")))
}
test("sample #3") {
assert(cover(List("##", "##")) === Some(List("""/\""", """\/""")))
}
test("sample case") {
val input = """3
2 3
###
###
1 1
.
4 5
.##..
.####
.####
.##..""".lines
val expected = """Case #1:
Impossible
Case #2:
.
Case #3:
./\..
.\//\
./\\/
.\/.. """.lines
lineComparison(input, expected)
}
ignore("full small case") {
val input = io.Source.fromFile("B-small-practice.in").getLines()
val expected = io.Source.fromFile("b.small.out.ref").getLines()
lineComparison(input, expected)
}
ignore("full large case") {
val input = io.Source.fromFile("B-large-practice.in").getLines()
val expected = io.Source.fromFile("b.large.out.ref").getLines()
lineComparison(input, expected)
}
def lineComparison(input: Iterator[String], expected: Iterator[String]) {
process(input) { s =>
for (line <- s.lines) assert(line.trim === expected.next().trim)
}
assert(expected.hasNext === false)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment