Skip to content

Instantly share code, notes, and snippets.

@bjartek
Created April 1, 2011 10:27
Show Gist options
  • Save bjartek/897985 to your computer and use it in GitHub Desktop.
Save bjartek/897985 to your computer and use it in GitHub Desktop.
class MineSweeper(val input:String) {
val grid = input.split("\n").map(_.toArray)
def isCellBomb(cell:(Int, Int)) = {
for{
row <- grid.lift(cell._1)
cell <- row.lift(cell._2)
if(cell == '*')
} yield 1
}
private def nearbyCells(x:Int, y:Int) = {
for{
row <- x-1 to x+1
col <- y-1 to y+1
} yield (row,col)
}
private def score(x:Int, y:Int) : String = isCellBomb(x,y) match {
case Some(_) => " "
case None => nearbyCells(x,y).flatMap(isCellBomb).sum.toString
}
def solve() = grid.indices.map( x => grid(x).indices.map( y => score(x,y)))
}
object MineSweeper {
def apply(input:String) = {
new MineSweeper(input);
}
}
val input = "..*\n...\n*..";
val sollution = MineSweeper(input).solve()
sollution.foreach(x => println(x.mkString))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment