Eight queens puzzle (Scala)

From LiteratePrograms

Jump to: navigation, search
Other implementations: C | Erlang | Forth | J | Scala

This program is a code dump.
Code dumps are articles with little or no documentation or rearrangement of code. Please help to turn it into a literate program. Also make sure that the source of this code does consent to release it under the MIT or public domain license.


object EightQueens extends Application {
  def isSafe(queens: List[Int], column: Int, delta: Int): Boolean =
    queens.isEmpty || 
      ((queens.head != column) && 
      (Math.abs(queens.head - column) != delta) &&
      isSafe(queens.tail, column, delta+1))

  def queens(n: Int): List[List[Int]] = {
    def placeQueens(k: Int): List[List[Int]] =
      if (k == 0) List(List())
      else for { queens <- placeQueens(k - 1)
                 column <- (1 to n)
                 if isSafe(queens, column, 1) } yield column :: queens
    placeQueens(n)
  }
  queens(8).foreach(println(_))
}


TODO
Finish this solution
Download code
Personal tools