Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,907 questions

51,839 answers

573 users

How to fill a 3x3 grid to be a valid Sudoku grid in JavaScript

1 Answer

0 votes
// To fill a 3x3 grid to be a valid Sudoku grid, you must ensure that each row, 
// column, and the 3x3 grid contains the numbers 1 through 9 without repetition.

function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
}

// Function to fill the Sudoku grid
function fillSudokuGrid() {
    let numbers = [...Array(9).keys()].map(n => n + 1);

    // Shuffle the numbers randomly
    shuffleArray(numbers);

    // Fill the 3x3 grid row by row
    let grid = Array.from({ length: 3 }, () => Array(3).fill(0));
    let index = 0;

    for (let i = 0; i < 3; i++) {
        for (let j = 0; j < 3; j++) {
            grid[i][j] = numbers[index++];
        }
    }

    return grid;
}

// Function to print the grid
function printGrid(grid) {
    grid.forEach(row => console.log(row.join(' ')));
}

// Initialize and fill the 3x3 grid
let grid = fillSudokuGrid();

// Print the grid
console.log("Generated 3x3 Sudoku Grid:");
printGrid(grid);

  
  
/*
run:
      
Generated 3x3 Sudoku Grid:
7 3 5
9 6 2
1 4 8

*/
 

 



answered Jun 1, 2025 by avibootz
edited Jun 1, 2025 by avibootz

Related questions

...