Created
November 21, 2017 10:45
-
-
Save brendanmaguire/1afc2baf5bbf58e6702859881ecb8859 to your computer and use it in GitHub Desktop.
Solution to http://codingdojo.org/kata/Minesweeper/ - Functional Kubs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object Minesweeper extends App { | |
/* | |
* Solution to http://codingdojo.org/kata/Minesweeper/ (sort of, doesn't read from stdin) | |
*/ | |
type Row = Int | |
type Col = Int | |
def emptyMap= Map[(Row, Col), Int]().withDefaultValue(0) | |
val rowLen = 4 | |
val colLen = 4 | |
val simpleInput = | |
""" | |
*... | |
.... | |
.*.. | |
.... | |
""".stripMargin | |
val simpleInputWithoutSpaces = simpleInput.replaceAll("\n", "") | |
def findSurroundingCells(row: Row, col: Col) = | |
for (x <- row - 1 to row + 1; y <- col - 1 to col + 1) yield (x,y) | |
def findCell(idx: Int, col: Col): (Row, Col) = (idx / col, idx % col) | |
val answer = simpleInputWithoutSpaces.zipWithIndex.foldLeft(emptyMap) { | |
case (counts, ('*', idx)) => | |
val cell = findCell(idx, colLen) | |
val x = findSurroundingCells(cell._1, cell._2) map { _ -> 1 } | |
x.toMap ++ counts.map{ case (k,v) => k -> (v + x.toMap.getOrElse(k, 0)) } | |
case (counts, (_, _)) => counts | |
} | |
simpleInputWithoutSpaces.zipWithIndex foreach { | |
case (char, idx) => | |
(char, idx) match { | |
case ('.', idx) => print(answer.getOrElse(findCell(idx, colLen), 0)) | |
case ('*', _) => print('*') | |
} | |
if (idx % colLen == colLen - 1) println() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment