So I’m making a basic brute force sudoku solver. I created a class that takes in a board string and use a constructor to set this.board = board parameter passed in
export default class SudokuSolver {
constructor(board){
this.board = board
}
the first method that gets run is 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’s say for example pass in:
let boardString = "1024091501202523235" //imagine this is a valid board string
const board = new SudokuSolver(boardString)
console.log(board.validBoardFormat())
console: true
This works perfectly fine on its own.
later in the class I define a solve method
solve(){
if (this.validBoardFormat()){
this.validBoardFormat()
this.configureBoardArray()
this.solveBoard()
} else {
console.log('Board error')
}
}
The issue is when I pass this:
let boardString = "1024091501202523235" //imagine this is a valid board string
const board = new SudokuSolver(board)
console.log(board.solve())
and I run it on liveserver, I am getting this error:
Uncaught TypeError: this.board.split is not a function in the validBoardFormat function
I have been trying to troubleshoot this for a while now any help would be appreicated
>Solution :
You’re setting this.board to an array:
if (cleanedBoard.length === 81){
this.board = cleanedBoard // <= this.board is now an array
return true
}
So the next time you call validBoardFormat() you end up trying to invoke split on the array, not the string:
let uncleanedBoard = this.board.split('') // this.board is now an array, not a string