簡體   English   中英

在數組的數組上使用 math.random 的問題

[英]problem using math.random on array of arrays

我在學校有一個制作數獨游戲的項目,當我嘗試從出現在 html 中的數組中應用隨機數獨時遇到問題,當我使用非隨機數獨時它工作正常,但是當我使用隨機數獨作為矩陣一切都搞砸了,並在每個輸入中給我一個完整的數組

//this is the 9x9 matrix and there are 3 more
let sudoku1 = [
    [8, 2, 7, 1, 5, 4, 3, 9, 6],
    [9, 6, 5, 3, 2, 7, 1, 4, 8],
    [3, 4, 1, 6, 8, 9, 7, 5, 2],
    [5, 9, 3, 4, 6, 8, 2, 7, 1],
    [4, 7, 2, 5, 1, 3, 6, 8, 9],
    [6, 1, 8, 9, 7, 2, 4, 3, 5],
    [7, 8, 6, 2, 3, 5, 9, 1, 4],
    [1, 5, 4, 7, 9, 6, 8, 2, 3],
    [2, 3, 9, 8, 4, 1, 5, 6, 7]];
//these are the array of sudokus(each sudoku is a 9x9 matrix)
let allSudokus = [[sudoku1], [sudoku2], [sudoku3], [sudoku4]]
let randomSudoku = allSudokus[Math.floor(Math.random() * allSudokus.length)]

//this is the function i did in order to fill "solve" the board
const solveBoard = () => {
    for (let r = 0; r < 9; r++) {
        for (let c = 0; c < 9; c++) {
            let cellid = document.querySelector("#r" + r + "c" + c); //
            cellid.innerHTML = randomSudoku[r][c]
        }
    }
}

這就是我使用 randomSudoku 時發生的情況

這是我使用數獨1的時候

您正在使用allsudokus (不存在)而不是allSudokus 做這個:

let randomSudoku = allSudokus[Math.floor(Math.random() * allSudokus.length)]

然后在這里:

cellid.innerHTML = randomSudoku[r][c]

編輯:好的,你現在解決了這個問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM