tasks a-s
This commit is contained in:
parent
47bf37c096
commit
b83f433714
12433 changed files with 156208 additions and 123 deletions
20
Task/N-queens-problem/Scala/n-queens-problem.scala
Normal file
20
Task/N-queens-problem/Scala/n-queens-problem.scala
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
case class Pos(row: Int, column: Int) {
|
||||
def sameRow(p: Pos) = row == p.row
|
||||
def sameColumn(p: Pos) = column == p.column
|
||||
def sameDiag(p: Pos) = (p.column - column).abs == (p.row - row).abs
|
||||
def illegal(p: Pos) = sameRow(p) || sameColumn(p) || sameDiag(p)
|
||||
def legal(p: Pos) = !illegal(p)
|
||||
}
|
||||
|
||||
def rowSet(size: Int, row: Int) = Iterator.tabulate(size)(column => Pos(row, column))
|
||||
|
||||
def expand(solutions: Iterator[List[Pos]], size: Int, row: Int) =
|
||||
for {
|
||||
solution <- solutions
|
||||
pos <- rowSet(size, row)
|
||||
if solution forall (_ legal pos)
|
||||
} yield pos :: solution
|
||||
|
||||
def seed(size: Int) = rowSet(size, 0) map (sol => List(sol))
|
||||
|
||||
def solve(size: Int) = (1 until size).foldLeft(seed(size)) (expand(_, size, _))
|
||||
Loading…
Add table
Add a link
Reference in a new issue