added assignment 6 ex 4

This commit is contained in:
Louis Heredero 2025-04-08 15:52:54 +02:00
parent f4e417571a
commit 056305fd72
Signed by: HEL
GPG Key ID: 8D83DE470F8544E7

39
src/Assignment6/Ex4.sc Normal file
View File

@ -0,0 +1,39 @@
def inCheck(q1: (Int, Int), q2: (Int, Int)) =
q1._1 == q2._1 || // same row
q1._2 == q2._2 || // same column
(q1._1 - q2._1).abs == (q1._2 - q2._2).abs // on diagonal
def isSafe(queen: (Int, Int), queens: List[(Int, Int)]) =
queens forall (q => !inCheck(queen, q))
def queens(n: Int): List[List[(Int, Int)]] = {
def placeQueens(k: Int): List[List[(Int, Int)]] =
if (k == 0)
List(List())
else
for {
queens <- placeQueens(k - 1)
column <- 1 to n
queen = (k, column)
if isSafe(queen, queens)
} yield queen :: queens
placeQueens(n)
}
def printChessBoard(solutions: List[List[(Int, Int)]]): String = {
val sols: List[String] = for ((sol, i) <- solutions.zipWithIndex) yield {
val lines: IndexedSeq[String] = for (y <- 1 to sol.length) yield {
val line: IndexedSeq[String] = {
for (x <- 1 to sol.length) yield {
if (sol contains (y, x)) "" else "_"
}
}
line.mkString("|", "|", "|")
}
s"Solution $i:\n" + lines.mkString("\n")
}
sols.mkString("\n\n")
}
println(printChessBoard(queens(4)))