Advertisement
Guest User

fig fig

a guest
Apr 15th, 2014
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.79 KB | None | 0 0
  1. object Start extends App {
  2.  
  3.   val fieldSize = 8
  4.  
  5.   case class Figure(point: (Int, Int), config: FigureConfig) {
  6.  
  7.     private def withinBounds(p: (Int, Int)): Boolean = {
  8.       def within(i: Int) = i > 0 || i <= fieldSize
  9.       within(p._1) && within(p._2)
  10.     }
  11.  
  12.     def beats(cell: (Int, Int)): Boolean = {
  13.       withinBounds(cell) && (cell == point || config.beatsCell(cell, point))
  14.     }
  15.  
  16.   }
  17.  
  18.   trait FigureConfig {
  19.     def beatsCell(cell: (Int, Int), point: (Int, Int)): Boolean = false
  20.   }
  21.  
  22.   trait DiagonalFigureConfig extends FigureConfig {
  23.     override def beatsCell(cell: (Int, Int), point: (Int, Int)): Boolean = Math.abs(point._1 - cell._1) == Math.abs(point._2 - cell._2) || super.beatsCell(cell, point)
  24.   }
  25.  
  26.   trait LineFigureConfig extends FigureConfig {
  27.     override def beatsCell(cell: (Int, Int), point: (Int, Int)): Boolean = (cell._1 == point._1) || (cell._2 == point._2) || super.beatsCell(cell, point)
  28.   }
  29.  
  30.   case object QueenConfig extends DiagonalFigureConfig with LineFigureConfig
  31.  
  32.   case object BishopConfig extends DiagonalFigureConfig
  33.  
  34.   case object RockConfig extends LineFigureConfig
  35.  
  36.   def solveWithOpenedCells(openCells: List[(Int, Int)], figs: List[FigureConfig]): List[List[Figure]] = {
  37.     if (figs.isEmpty) {
  38.       List(Nil)
  39.     } else {
  40.       for (
  41.         openCell <- openCells;
  42.         r = Figure(openCell, figs.head);
  43.         rest <- solveWithOpenedCells(openCells.filterNot(r.beats), figs.tail)
  44.       ) yield r :: rest
  45.     }
  46.   }
  47.  
  48.   def solve(figs: List[FigureConfig]): List[List[Figure]] = {
  49.     val opened = for (x <- 1 until fieldSize + 1; y <- 1 until fieldSize + 1) yield (x, y)
  50.     solveWithOpenedCells(opened.toList, figs)
  51.   }
  52.  
  53.   val figures = List(QueenConfig, QueenConfig, RockConfig)
  54.  
  55.   solve(figures).foreach(println)
  56.  
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement