我有这段代码
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变量。我知道这些是可变变量。但是,我被告知我不能在我的任务中使用这些var。 似乎我不能简单地将它们更改为val,因为val是一个不可变的引用,我重新分配了var的值。
那么我怎样才能将这些var变量更改为val?如果我的代码,我是否需要重新考虑结构?
答案 0 :(得分: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
}
}
}