2012-01-17 20 views
0

私はScintでGameOfLifeを解決しようとしています。私はセル(x、y)のセットとしてグリッドを表現しようとしています。私が(0,0)で始まるストリングから読むと。 しかし、GameOfLifeの法則のため、私はGenerationクラスにルールを適用した後、Infinite Gridを検討しているので、現在の世代を印刷したいと思います。Scalaのデカルト座標の最小値と最大値の求め方

ここでは、生き残りセルの 'X'とその世代のGameOfLifeの死んだセルの ' - 'の反復と印刷を開始する場所から最小位置(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ここで、CellはCell(x、y)のケースクラスであるSet [Cell]です。

答えて

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 

などを。

関連する問題