Created
July 29, 2018 19:07
-
-
Save ASRagab/5ab2bd55e90324eaa9bd320b3d172849 to your computer and use it in GitHub Desktop.
Brute Force nQueens
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 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