2016-04-03 4 views
-1

У меня есть этот кусок кодаИзменение переменных вар ВАЛ

object Sudoku extends SudokuLikeGame { 
    type T = Board 

    def parse(str: String): Board = { 
     // helper method to filter out whether or not the coordinate given is mapped for one 
     // value and then must check for the rest of the peers 
     def parseHelper(board: Map[(Int, Int), List[Int]], 
         row: Int, col: Int): Map[(Int, Int), List[Int]] = { 
     var parseBoard = board 
     val oldValues = parseBoard(row, col).head//takes the first value 
     for(r <- 0 to 8; c <- 0 to 8){ 
      //iterates the list of peers from peers() and if at the row and col has a value 
      //contained within the board passed in 
      for {(r, c) <- Solution.peers(row, col) 
       if (parseBoard(r, c).contains(oldValues))} { 
      //removes all the old values from 
      val newValue = parseBoard(r, c) diff List(oldValues) 
      //removes all the old values at the coord r, c and maps it to the correct value 
      parseBoard = (parseBoard - ((r, c))) + ((r, c) -> newValue) 
      if(newValue.size == 1) //one value means no more peers 
       parseBoard = parseHelper(board, r, c) 
     } 
     } 
     parseBoard 
    } 

    var sudokuBoard = Map[(Int, Int), List[Int]]() 
    if(str.length == 81){ 
     str 
    } 
    else{ 
     println("insuffient length") 
     System.exit(1) 
    } 

я написал некоторые Var переменные. Я знаю, что это переменные переменные. Однако мне сказали, что я не могу использовать эти переменные в моем задании. Не похоже, что я могу просто изменить их на val, потому что val является неизменной ссылкой, и я reassignimg значение var.

Так как бы я мог изменить эти переменные var на val? Должен ли я переосмыслить структуру, если мой код?

+0

Ваш 'for' может стать' foldLeft', где вы проходите как аккумулятор текущее значение parseBoard. Это позволит вам избежать изменчивого 'parseBoard' –

+0

Кроме того, я думаю, что есть ошибка - ваш внешний цикл итерации над доской, но вы никогда не используете значения' r' и 'c' - они затенены теми, в вашей внутренней петле –

ответ

0

Это должно быть сделано (непроверено, так как нам не хватает какого-либо материала из вашего кода и угадывает, что делает Solution.peers). Вместо изменения parseBoard мы используем foldLeft (дважды), чтобы передать новую доску к следующему шагу

def peers(row:Int, col:Int) = { 
    val rs = for (r <- 0 to 8 if r != row) yield (r, col) 
    val cs = for (c <- 0 to 8 if c != col) yield (row, c) 
    rs ++ cs 
    } 
    val cells = for (r <- 0 to 8; c <- 0 to 8) yield (r,c) 


def parseHelper(board: Map[(Int, Int), List[Int]], 
       row: Int, col: Int): Map[(Int, Int), List[Int]] = { 
    val oldValues = board((row, col)).head //takes the first value 
    cells.foldLeft(board) { 
    case (b1, (r, c)) => 
    //iterates the list of peers from peers() and if at the row and col has a value 
    //contained within the board passed in 
    peers(row, col).foldLeft(b1) { 
     case (b, (r, c)) => 

     if (b((r, c)).contains(oldValues)) { 
      //removes all the old values from 
      val newValue = b((r, c)) diff List(oldValues) 
      //removes all the old values at the coord r, c and maps it to the correct value 
      if (newValue.size == 1) parseHelper(board, r, c) else b - ((r, c)) + ((r, c) -> newValue) 
     } else b 
    } 
    } 
} 
Смежные вопросы