所以我正在制作一个基本的蛮力数独求解器。我创建了一个类,它接受一个板字符串,并使用构造函数来设置这个。board=中传递的板参数
export default class SudokuSolver {
constructor(board){
this.board = board
}
运行的第一个方法是validBoardFormat
validBoardFormat(){
/* possible input formats: CSV of 81 integers or string of 81 integers
0's replace unknown numbers*/
let cleanedBoard=[];
let uncleanedBoard = this.board.split('') //split by character
for (let i = 0; i<uncleanedBoard.length; i++){
if (this.validNum(uncleanedBoard[i])){ //validate with validNum function
cleanedBoard.push(parseInt(uncleanedBoard[i]))
}
}
if (cleanedBoard.length === 81){
this.board = cleanedBoard //make sure board matches correct sudoku board length
return true
}
return false
}
比方说传入:
let boardString = "1024091501202523235" //imagine this is a valid board string
const board = new SudokuSolver(boardString)
console.log(board.validBoardFormat())
console: true
这本身就非常好。
在课程的后面,我定义了一个求解方法
solve(){
if (this.validBoardFormat()){
this.validBoardFormat()
this.configureBoardArray()
this.solveBoard()
} else {
console.log('Board error')
}
}
问题是当我通过这个:
let boardString = "1024091501202523235" //imagine this is a valid board string
const board = new SudokuSolver(board)
console.log(board.solve())
我在liveserver上运行它,我得到了这个错误:
validBoardFormat函数中的Uncaught TypeError: this.board.split is not a function
我已经尝试解决这个问题有一段时间了,现在任何帮助都将被认为是
您正在将this.board
设置为数组:
if (cleanedBoard.length === 81){
this.board = cleanedBoard // <= this.board is now an array
return true
}
因此,下次调用validBoardFormat()
时,您最终会尝试在数组上调用split
,而不是字符串:
let uncleanedBoard = this.board.split('') // this.board is now an array, not a string
您不能执行const board = new SudokuSolver(board)
,因为板变量尚未定义。你需要做const board = new SudokuSolver(boardString)
。
我现在意识到,在我的求解方法中,我在if语句本身中执行validBoardFormat,它将this.board的值从字符串(原始输入(更改为数组。在通过if语句后,它再次运行this.validBoardFormat,但现在this.board是一个数组,所以它不能再执行.split((了。
为了解决这个问题,我已经将this.validBoardFormat的返回存储在一个变量中,然后使用该值继续
solve(){
let validation = this.validBoardFormat()
if (validation){
this.configureBoardArray()
this.solveBoard()
return this.board
} else {
console.log('Board error')
}
}
奇怪的是,当你在之前盯着它看了很长一段时间后终于寻求帮助时,你能多么快地发现自己的错误lmao