From 814f72eef9a60563b45efd2fc21da0776312b8f9 Mon Sep 17 00:00:00 2001 From: pm6lnt93v <1289474397@qq.com> Date: Tue, 5 Nov 2024 17:19:18 +0800 Subject: [PATCH] ADD file via upload --- 2.c | 71 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 2.c diff --git a/2.c b/2.c new file mode 100644 index 0000000..df6fb79 --- /dev/null +++ b/2.c @@ -0,0 +1,71 @@ +#include +#include +#include + +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; +} \ No newline at end of file