```
object Example {
def inCheck(q1: (Int, Int), q2: (Int, Int)) = {
q1._1 == q2._1 ||
q1._2 == q2._2 ||
(q1._1 - q2._1).abs == (q1._2 - q2._2).abs
}
def isSafe(queen: (Int, Int), queens: List[(Int, Int)]) = {
queens.forall(!inCheck(_, queen))
}
def queens(k: Int): List[List[(Int, Int)]] = {
// solve the nth row
def placeQueens(n: Int): List[List[(Int, Int)]] = {
if (n == 0) {
List(List())
}
else {
for {
queens: List[(Int, Int)] <- placeQueens(n - 1)
column <- 1 to k
queen = (n, column)
if (isSafe(queen, queens))
} yield queen :: queens
}
}
placeQueens(k)
}
}
object Test {
import Example._
isSafe((1, 1), List((2, 3), (3, 2)))
inCheck((1, 1), (2, 3))
List[Int]().forall(_ > 3) // vacuously true
queens(4)
}
```

## Friday, October 16, 2015

Subscribe to:
Post Comments (Atom)

## 0 comments:

Post a Comment