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

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,705 questions

55,464 answers

573 users

How to fill a 3x3 grid to be a valid Sudoku grid in C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <algorithm> // shuffle
#include <random>

// 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.

void fillSudokuGrid(std::vector<std::vector<int>>& grid) {
    // Create a vector with numbers 1 to 9
    std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};

    // Shuffle the numbers randomly
    std::random_device rd;
    std::mt19937 g(rd());
    std::shuffle(numbers.begin(), numbers.end(), g);

    // Fill the 3x3 grid row by row
    int index = 0;
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 3; ++j) {
            grid[i][j] = numbers[index++];
        }
    }
}

void printGrid(const std::vector<std::vector<int>>& grid) {
    for (const auto& row : grid) {
        for (int num : row) {
            std::cout << num << " ";
        }
        std::cout << "\n";
    }
}

int main() {
    // Initialize an empty 3x3 grid
    std::vector<std::vector<int>> grid(3, std::vector<int>(3, 0));

    // Fill the grid with a valid Sudoku configuration
    fillSudokuGrid(grid);

    // Print the grid
    std::cout << "Generated 3x3 Sudoku Grid:\n";
    printGrid(grid);
}



/*
run:

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

*/

 



answered Jun 1, 2025 by avibootz

Related questions

1 answer 134 views
1 answer 140 views
1 answer 213 views
1 answer 173 views
1 answer 182 views
1 answer 204 views
...