Page 486 (PDF page 521):
A nice addition to the n-queens problem would be to print all possible
solutions to the console in a nice format:
________________
|Q|_|_|_|_|_|_|_|
|_|_|_|_|Q|_|_|_|
|_|_|_|_|_|_|_|Q|
|_|_|_|_|_|Q|_|_|
|_|_|Q|_|_|_|_|_|
|_|_|_|_|_|_|Q|_|
|_|Q|_|_|_|_|_|_|
|_|_|_|Q|_|_|_|_|
________________
|Q|_|_|_|_|_|_|_|
|_|_|_|_|_|Q|_|_|
|_|_|_|_|_|_|_|Q|
|_|_|Q|_|_|_|_|_|
|_|_|_|_|_|_|Q|_|
|_|_|_|Q|_|_|_|_|
|_|Q|_|_|_|_|_|_|
|_|_|_|_|Q|_|_|_|
...
// This could probably be written differently, but nevertheless, here is
the code:
def printSolutions(tbls: List[List[(Int, Int)]]) = {
def printSolution(tbl: List[(Int, Int)]) = {
val len = tbl.head._1 // since it's upside down
println("_" * (len * 2))
for {
dim <- tbl.reverse
col <- 1 to len // we put something in every cell
pipe = if (col == 1) "|" else ""
cell = if (col == dim._2) "Q|" else "_|"
nl = if (col == len) "\n" else ""
} print(pipe + cell + nl)
}
for (t <- tbls) printSolution(t)
}
|