You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
71 lines
1.5 KiB
71 lines
1.5 KiB
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <time.h>
|
|
|
|
void printMatrix(char matrix[9][9])
|
|
{
|
|
for (int i = 0; i < 9; i++)
|
|
{
|
|
for (int j = 0; j < 9; j++)
|
|
{
|
|
printf("%c ", matrix[i][j]);
|
|
}
|
|
printf("\n");
|
|
}
|
|
}
|
|
|
|
void generateRow(char row[9], int nums[9])
|
|
{
|
|
// Fill the row with '0'
|
|
for (int i = 0; i < 9; i++)
|
|
{
|
|
row[i] = '0';
|
|
}
|
|
|
|
// Place three unique numbers from the provided nums array into random positions
|
|
for (int i = 0; i < 3; i++)
|
|
{
|
|
int pos;
|
|
do
|
|
{
|
|
pos = rand() % 9;
|
|
} while (row[pos] != '0'); // Find an empty position
|
|
row[pos] = nums[i] + '0'; // Store as char
|
|
}
|
|
}
|
|
|
|
void generateUniqueRows(char matrix[9][9], int startRow) {
|
|
int nums[9] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
|
|
// Shuffle numbers
|
|
for (int i = 8; i > 0; i--) {
|
|
int j = rand() % (i + 1);
|
|
int temp = nums[i];
|
|
nums[i] = nums[j];
|
|
nums[j] = temp;
|
|
}
|
|
|
|
// Fill 3 rows with 3 unique numbers each
|
|
for (int i = 0; i < 3; i++) {
|
|
generateRow(matrix[startRow + i], nums + i * 3);
|
|
}
|
|
}
|
|
|
|
int main() {
|
|
srand(time(NULL)); // Set random seed
|
|
|
|
char matrix[9][9];
|
|
|
|
// Generate the first three rows
|
|
generateUniqueRows(matrix, 0);
|
|
|
|
// Generate the next three rows
|
|
generateUniqueRows(matrix, 3);
|
|
|
|
// Generate the last three rows
|
|
generateUniqueRows(matrix, 6);
|
|
|
|
// Print the matrix
|
|
printMatrix(matrix);
|
|
|
|
return 0;
|
|
} |