我正在嘗試驗證 Soduko 板。我的輸入是 Any 型別,所以首先,我想將其更改為 Int。并驗證這一點,我撰寫了以下代碼,但它無法回傳真實結果并回傳一些錯誤。我該如何處理代碼問題?validate 方法由另外兩種方法組成,一種用于將 Any 轉換為 Int,另一種用于驗證 Sudoko 板。
def validate(lines: Array[Option[Any]]*): Boolean = {
object BoardParser {
/**
* Parse a Sudoku board from varargs
* Board needs to have 9 rows, 9 columns & all Int or Long values for non-empty cells, to be accepted
*
* @param board Variable number of optional arrays
* @return A 2D Int array representing the basic Sudoku board
*/
def getValidBoard(board: Array[Option[Any]]*): Array[Array[Int]] = {
def validateBoard() = {
if (board.length != 9 || board.transpose.length != 9) {
throw new IllegalArgumentException("Board must be a 2D array of size 9x9")
} else if (!board.forall(isAllNumbers)) {
throw new IllegalArgumentException("Board must contain only Int or Long values")
}
}
validateBoard()
board.map(toNumbers).toArray
}
private def isAllNumbers(line: Array[Option[Any]]) = {
line.forall {
case Some(_: Int) => true
case Some(_ : Long) => true
case None => true
case _ => false
}
}
private def toNumbers(line: Array[Option[Any]]) = {
line.map {
case Some(x: Int) => x
case Some(x: Long) => x.toInt
case None => 0
case _ => throw new IllegalArgumentException
}
}
}
val valid_board = getValidBoard(lines)
def new_validate(board: Array[Array[Int]]): Boolean = {
lazy val rowsValid = board.forall(hasNoDuplicates)
lazy val columnsValid = board.transpose.forall(hasNoDuplicates)
lazy val cellsValid = squaresHaveNoDuplicates(board)
rowsValid && columnsValid && cellsValid
}
private def hasNoDuplicates(line: Array[Int]) = line.distinct.count(1 to 9 contains _) == line.count(_ != 0)
private def squaresHaveNoDuplicates(matrix: Array[Array[Int]]) = {
val rowBlocks = matrix.grouped(3).toArray
val transposed = rowBlocks.map(_.transpose)
val squares = transposed.map(_.grouped(3).toArray)
val squaresFlattened = squares.map(_.map(_.flatten))
squaresFlattened.forall(_.forall(hasNoDuplicates))
}
return new_validate(valid_board)
uj5u.com熱心網友回復:
您hasNoDuplicates在def. private是僅在object,class或的直接范圍內的有效修飾符trait。def無論如何,嵌套的s 將僅在外部def本身的范圍內可見,因此private在那里沒有意義。您可以選擇:
- 洗掉
private修飾符,或 - 移動
hasNoDuplicates之外validate(但請記住這只會使意義它是private,如果它在一個直接范圍object,class或trait)
第一個更容易,但總的來說,我建議您考慮是否可以減少使用 nesting def。當然,這由你來判斷。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/361523.html
標籤:斯卡拉
