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 <stdio.h>
#include <stdlib.h>
#include <time.h>

// 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 to shuffle an array
void shuffle(int *array, int size) {
    for (int i = size - 1; i > 0; --i) {
        int j = rand() % (i + 1);
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

// Function to fill the Sudoku grid
void fillSudokuGrid(int grid[3][3]) {
    int numbers[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9};

    // Shuffle the numbers randomly
    shuffle(numbers, 9);

    // 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++];
        }
    }
}

// Function to print the grid
void printGrid(int grid[3][3]) {
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 3; ++j) {
            printf("%d ", grid[i][j]);
        }
        printf("\n");
    }
}

int main() {
    // Seed the random number generator
    srand(time(NULL));

    // Initialize an empty 3x3 grid
    int grid[3][3] = {0};

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

    // Print the grid
    printf("Generated 3x3 Sudoku Grid:\n");
    printGrid(grid);

    return 0;
}



/*
run:

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

*/

 



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

Related questions

1 answer 101 views
1 answer 153 views
1 answer 213 views
1 answer 173 views
1 answer 182 views
1 answer 204 views
...