-
-
Save scvalencia/608d965ad64f12fff2c370128b22fe44 to your computer and use it in GitHub Desktop.
Solution to the n-Queen puzzle (https://en.wikipedia.org/wiki/Eight_queens_puzzle)
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
def nQueens(n: Int) = (0 until n).permutations filter {p => // p[i] is the column of the queen on ith row (must be a permutation of 0 until n) | |
val i = p.zipWithIndex.toSet | |
i.map{case (c, d) => c + d}.size == n && i.map{case (c, d) => c - d}.size == n // No 2 queens can have same col + diag or col - diag | |
} | |
for { | |
(solution, num) <- nQueens(8).zipWithIndex | |
_ = println(s"Solution #${num + 1}:") | |
col <- solution | |
row = solution.indices.map(i => if (i == col) 'Q' else '-') | |
} println(row.mkString) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment