Created
November 1, 2013 16:16
-
-
Save logicmason/7267772 to your computer and use it in GitHub Desktop.
This nQueens solution in Scala is surprisingly verbose compared to the JS versions I've seen. I'm still a beginner though, working through the Coursera class by Martin Odersky.
This file contains hidden or 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 nQueens { | |
def queens(n: Int): Set[List[Int]] = { | |
def placeQueens(k: Int): Set[List[Int]] = | |
if (k == 0) Set(List()) | |
else | |
for { | |
queens <- placeQueens(k - 1) | |
col <- 0 until n | |
if isSafe(col, queens) | |
} yield col :: queens | |
placeQueens(n) | |
} | |
Int)Set[List[Int]] | |
def isSafe(col: Int, queens: List[Int]): Boolean = { | |
val row = queens.length | |
val queensWithRow = (row - 1 to 0 by -1) zip queens | |
queensWithRow forall { | |
case (r, c) => col != c && math.abs(col - c) != row -r | |
} | |
} | |
Int, queens: List[Int])Boolean | |
def show(queens: List[Int]) = { | |
val lines = | |
for (col <- queens.reverse) | |
yield Vector.fill(queens.length)("* ").updated(col, "Q ").mkString | |
"\n\n" + (lines mkString "\n") | |
} | |
List[Int])String | |
(queens(12) map show) mkString "\n" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment