我嘗試了線上編輯器上的所有方法,但仍然收到錯誤。但當我在我的機器上的 VSCode 上執行此操作時,它工作正常。我很困惑,在沒有發現錯誤的情況下無法提交程式碼。我不知道該去哪裡找了。我希望有另一雙眼睛幫我看看這個。我真的很感激。
//puzzle let puzzle = [ [8, 9, 5, 7, 4, 2, 1, 3, 6], [2, 7, 1, 9, 6, 3, 4, 8, 5], [4, 6, 3, 5, 8, 1, 7, 9, 2], [9, 3, 4, 6, 1, 7, 2, 5, 8], [5, 1, 7, 2, 3, 8, 9, 6, 4], [6, 8, 2, 4, 5, 9, 3, 7, 1], [1, 5, 9, 8, 7, 4, 6, 2, 3], [7, 4, 6, 3, 2, 5, 8, 1, 9], [3, 2, 8, 1, 9, 6, 5, 4, 7], ]; //puzzle 2 let puzzleTwo = [ [8, 9, 5, 7, 4, 2, 1, 3, 6], [8, 7, 1, 9, 6, 3, 4, 8, 5], [4, 6, 3, 5, 8, 1, 7, 9, 2], [9, 3, 4, 6, 1, 7, 2, 5, 8], [5, 1, 7, 2, 3, 8, 9, 6, 4], [6, 8, 2, 4, 5, 9, 3, 7, 1], [1, 5, 9, 8, 7, 4, 6, 2, 3], [7, 4, 6, 3, 2, 5, 8, 1, 9], [3, 2, 8, 1, 9, 6, 5, 4, 7], ]; //DO NOT EDIT ABOVE function getRow(puzzle, row) { let array = []; for (let i = 0; i < puzzle.length; i++) { if (i === row) for (let j = 0; j < puzzle[i].length; j++) array.push(puzzle[i][j]); } return array; } function getColumn(puzzle, col) { let array = []; for (let i = 0; i < puzzle.length; i++) { for (let j = 0; j < puzzle[i].length; j++) if (j === col) array.push(puzzle[i][col]); } return array; } function getSection(puzzle, x, y) { let array = []; let xIndex = 0; let yIndex = 0; if (x === 0) yIndex = 0; else if (x === 1) yIndex = 3; else yIndex = 6; if (y === 0) xIndex = 0; else if (y === 1) xIndex = 3; else xIndex = 6; for (let i = xIndex; i < xIndex + 3; i++) for (let j = yIndex; j < yIndex + 3; j++) array.push(puzzle[i][j]); return array; } function includes1To9(arr) { let prev = arr[0]; for (let i = 1; i < arr.length; i++) { if (arr[i] === prev) return false; prev = arr[i]; } return true; } function sudokuIsValid(puzzle) { for (let x = 0; x < 3; x++) for (let y = 0; y < 3; y++) if (includes1To9(getSection(puzzle, x, y)) === false) return false; for (let i = 0; i < puzzle.length; i++) { if (includes1To9(getRow(puzzle, i)) === false) return false; if (includes1To9(getColumn(puzzle, i)) === false) return false; } return true; } console.log(sudokuIsValid(puzzle)); //Returns true console.log(sudokuIsValid(puzzleTwo)); //Returns false
這是我收到的錯誤訊息。當數獨無效時,提示要求我回傳 false。正如您所看到的,對於無效的謎題,它確實會傳回 false,但並非所有無效的謎題。
FAIL ./index.test.js sudoku sudokuIsValid ✓ returns false for an invalid puzzle (2 ms) ✕ returns false for other invalid puzzles (2 ms) ● sudoku sudokuIsValid › returns false for other invalid puzzles expect(received).toBe(expected) // Object.is equality Expected: false Received: true 21 | ]; 22 | let result = sudoku.sudokuIsValid(puzzle) > 23 | expect(result).toBe(false); | ^ 24 | }); 25 | 26 | }); at Object.<anonymous> (index.test.js:23:20)
您的
includes1To9()
僅檢查相鄰元素是否相同: