2012-01-17 4 views
0

나는 Infinte 그리드가있는 Scala에서 GameOfLife를 해결하려고합니다. 그리드를 셀 집합 (x, y)으로 나타내려고합니다. 내가 문자열을 읽을 때 (0,0)부터 시작합니다. 그러나 GameOfLife의 법칙 때문에, 그리고 Generation 클래스에 규칙을 적용한 후 Infinite Grid를 고려하고 있으므로 현재 세대를 인쇄하려고합니다.스칼라에서 직각 좌표의 최소값과 최대 값을 찾는 방법

여기 살아있는 셀에 대해 'X'를 반복하고 인쇄 할 위치에서 최소 위치 (x, y 반복자 읽기)를 계산하는 방법을 모르겠다. GameOfLife에서 죽은 셀에 대해 해당 Generation.I gener 클래스의 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 

등등을.

관련 문제