The Artima Developer Community


Errata for Programming in Scala, 2nd Edition
Chapter 23: For Expressions Revisited
Return to errata index.

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)
}

Page number: Book type: Paperback book PDF eBook
Book version: (Or build date. Found on back of title page.)
Your feedback:
Your name: (optional)
Your email address: (optional) (will not be published)

Copyright © 2024 Artima, Inc. All rights reserved.