0

無限のグリッドがあるScalaでGameOfLifeを解決しようとしています。グリッドをセルのセット(x、y)として表現しようとしています。私が言う文字列から読むとき、私は(0,0)から始めます。しかし、GameOfLifeの法則と、Generationクラスにルールを適用した後、Infinite Gridを検討しているため、現在の世代を印刷したいと思います。

ここでは、その世代のGameOfLifeで、生きているセルの場合は「X」、死んだセルの場合は「-」のいずれかを繰り返して印刷を開始する場所から最小位置(x、yイテレーターを読み取る)を計算する方法がわかりません。 GenerationクラスのtoStringメソッドのソリューション。しかし、私はそれにまったく満足していません。誰かがより良い解決策を提案できますか?

override def toString:String = 
   {
        val output:StringBuilder = new StringBuilder();
        val minOfRowColumn = for
        {
          cell <- aliveCells
          row = cell.row
          column = cell.column
        } yield if( row < column ) row else column

        val min = minOfRowColumn.min

        val maxOfRowColumn = for
        {
          cell <- aliveCells
          row = cell.row
          column = cell.column
        } yield if( row > column ) row else column

        val max = maxOfRowColumn.max

        var row = min;
        var column = min;

        while(row <= max)
        {
          while(column <= max)
          {
            if(aliveCells.contains(Cell(row,column)))
            {
              output.append('X')
            }
            else
              output.append('-')
            column = column + 1
          }
          output.append("\n");
          column = min
          row = row + 1
        }


        //remove the last new line addded.
        val indexOfNewLine = output.lastIndexOf("\n");
        if( -1 != indexOfNewLine )
        output.delete(indexOfNewLine,output.length());

        return output.toString();
   }

ここでのaliveCellsはSet[Cell]であり、CellはCell(x、y)のケースクラスです。

4

1 に答える 1

1

私は次のコードを提案します:

override def toString = {
  val min = aliveCells.iterator.flatMap(c => Seq(c.row, c.column)).min
  val max = aliveCells.iterator.flatMap(c => Seq(c.row, c.column)).max

  (min to max) map { row =>
    (min to max) map (col => if (aliveCells(Cell(row, col))) "X" else "-") mkString
  } mkString ("\n")
}

正方形のグリッドが特に必要ない場合は、最小/最大の列と行を分離することをお勧めします。

val minC = aliveCells.iterator.map(_.column).min

等々。

于 2012-01-17T08:14:55.860 に答える