Skip to content

Instantly share code, notes, and snippets.

@shkesar
Forked from pathikrit/NQueen.scala
Created April 10, 2016 18:25
Show Gist options
  • Save shkesar/59f88b64580496bc5ee5dede0a8a0fa4 to your computer and use it in GitHub Desktop.
Save shkesar/59f88b64580496bc5ee5dede0a8a0fa4 to your computer and use it in GitHub Desktop.
Solution to the n-Queen puzzle (https://en.wikipedia.org/wiki/Eight_queens_puzzle)
def nQueens(n: Int) = (0 until n).permutations filter {p =>
val i = p.zipWithIndex.toSet // p[i] is the column of the queen on ith row (must be a permutation of 0 until n)
i.map{case (c, d) => c + d}.size == n && // No 2 queens can have same col + diag
i.map{case (c, d) => c - d}.size == n // No 2 queens can have same 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