Last active
December 16, 2015 19:49
-
-
Save bmarcot/5487447 to your computer and use it in GitHub Desktop.
The ``N Queens'' problem in Scala.
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 queens(n: Int): Set[List[Int]] = { | |
def isSafe(col: Int, queens: List[Int]): Boolean = { | |
val row = queens.length | |
val queensWithRow = queens zip (row - 1 to 0 by -1) | |
queensWithRow.forall { | |
case (c, r) => c != col && (math.abs(col - c) != row - r) | |
} | |
} | |
def isSafe2(col: Int, queens: List[Int]): Boolean = { | |
val row = queens.length | |
def isSafe2Rec(queens: List[(Int, Int)]): Boolean = { | |
queens match { | |
case (c, r) :: xs => c != col && (math.abs(col - c) != row - r) && isSafe2Rec(xs) | |
case _ => true | |
} | |
} | |
isSafe2Rec(queens zip (row - 1 to 0 by -1)) | |
} | |
def queensRec(k: Int): Set[List[Int]] = { | |
if (k == 0) Set(List()) | |
else for { | |
queens <- queensRec(k - 1) | |
col <- 0 until n | |
if isSafe2(col, queens) | |
} yield col :: queens | |
} | |
queensRec(n) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment