Skip to content

Instantly share code, notes, and snippets.

@ASRagab
Created July 29, 2018 19:07
Show Gist options
  • Save ASRagab/5ab2bd55e90324eaa9bd320b3d172849 to your computer and use it in GitHub Desktop.
Save ASRagab/5ab2bd55e90324eaa9bd320b3d172849 to your computer and use it in GitHub Desktop.
Brute Force nQueens
object nQueens extends App {
type Solution = IndexedSeq[Int]
def createSolutions(n: Int): Seq[Solution] = {
(0 until n).permutations.toSeq
}
def verifySolution(s: Solution): Boolean = {
s.indices.combinations(2).forall(x => Math.abs(x(0) - x(1)) != Math.abs(s(x(0)) - s(x(1))))
}
def nQueens(n: Int): Seq[Solution] = {
(0 until n).permutations
.filterNot(s => s.indices
.combinations(2)
.exists(c => Math.abs(c(0) - c(1)) == Math.abs(s(c(0)) - s(c(1)))))
.toSeq
}
println(nQueens(8))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment