Skip to content

Instantly share code, notes, and snippets.

@scvalencia
Forked from pathikrit/NQueen.scala
Created April 10, 2016 14:38
Show Gist options
  • Save scvalencia/608d965ad64f12fff2c370128b22fe44 to your computer and use it in GitHub Desktop.
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)
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