Created
July 18, 2017 15:02
-
-
Save blancosj/2d534d31983ef7beca818703a9c4e33b to your computer and use it in GitHub Desktop.
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
import scala.annotation.tailrec | |
case class Pos(x: Int, y: Int) | |
object Queen { | |
def isSafe(a: Pos, b: Pos): Boolean = { | |
a.x != b.x && a.y != b.y && Math.abs(a.x - b.x) != Math.abs(a.y - b.y) | |
} | |
def isSafe(a: Pos, queens: List[Pos]): Boolean = queens match { | |
case Nil => true | |
case _ => queens.forall(isSafe(a, _)) | |
} | |
@tailrec | |
def findListSafe(listQueens: List[Pos]): Boolean = { | |
listQueens match { | |
case Nil => true | |
case x :: xs => isSafe(x, xs) && findListSafe(xs) | |
} | |
} | |
} | |
(for (x <- List(Nil); y <- 0 to 5) yield (x, y)).foreach(println) | |
def calculateQueens(y: Int, n: Int): Vector[List[Pos]] = { | |
if (y < 0) | |
Vector(Nil) | |
else | |
for ( | |
queens <- calculateQueens(y - 1, n); | |
x <- 0 to n if (Queen.isSafe(Pos(x, y), queens))) | |
yield Pos(x, y) +: queens | |
} | |
val size = 12 | |
val combinations = calculateQueens(size, size) | |
def printBoard(size: Int, listQueens: List[Pos]) = { | |
for (y <- 0 to size) { | |
for (x <- 0 to size) { | |
if (listQueens.contains(Pos(x, y))) | |
print("Q ") | |
else | |
print("* ") | |
} | |
println() | |
} | |
} | |
printBoard(size, combinations.collectFirst { case i => i }.head) | |
/* | |
Q * * * * * * * * * * * * | |
* * Q * * * * * * * * * * | |
* * * * Q * * * * * * * * | |
* Q * * * * * * * * * * * | |
* * * * * * * * Q * * * * | |
* * * * * * * * * * * Q * | |
* * * * * * * * * Q * * * | |
* * * * * * * * * * * * Q | |
* * * Q * * * * * * * * * | |
* * * * * Q * * * * * * * | |
* * * * * * * Q * * * * * | |
* * * * * * * * * * Q * * | |
* * * * * * Q * * * * * * | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment