src/main/scala/Queens.scala

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import scala.collection.mutable.ArrayBuffer

case class Position(x: Int, y: Int) {
  def sameRow(other: Position) = x == other.x
  def sameCol(other: Position) = y == other.y
  def sameDiagonal(other: Position) = math.abs(x - other.x) == math.abs(y - other.y)
}

case class Queens() {
  val BoardRows = 8
  val BoardCols = 8

  def boardString(queen1: Option[Position], queen2: Option[Position]) = {
    def boardSquare(pos: Position) = pos match {
      case p if p == queen1.getOrElse() => 'W'
      case p if p == queen2.getOrElse() => 'B'
      case _ => '_'
    }

    val board = for (
      row <- (0 until BoardRows);
      col <- (0 until BoardCols)
    ) yield boardSquare(Position(row, col))

    board.grouped(BoardRows).map(_.mkString(" ")).mkString("\n") + '\n'
  }

  def canAttack(queen1: Position, queen2: Position) =
    (queen1 sameRow queen2) ||
    (queen1 sameCol queen2) ||
    (queen1 sameDiagonal queen2)
}

@abo64 and @rpridemore think this looks great

Comments


You're not logged in right now. Please login via GitHub to comment