From 74743eefb7139b3743f505b109768cbaad788b0c Mon Sep 17 00:00:00 2001 From: p89ykz7mv <1609456732@qq.com> Date: Fri, 1 Dec 2023 12:45:05 +0800 Subject: [PATCH] ADD file via upload --- T2.cpp | 116 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 T2.cpp diff --git a/T2.cpp b/T2.cpp new file mode 100644 index 0000000..dc934e1 --- /dev/null +++ b/T2.cpp @@ -0,0 +1,116 @@ +#include +#include +#include + +// 函数用于生成数字1到9的随机排列 +void shuffle(int arr[], int n) { + if (n > 1) { + int i; + for (i = 0; i < n - 1; i++) { + int j = i + rand() % (n - i); + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + } +} +//数独矩阵比较美观的输出 +void printSudoku(int sudoku[9][9]) { + printf("+-------+-------+-------+\n"); + for (int i = 0; i < 9; i++) { + if (i > 0 && i % 3 == 0) { + printf("+-------+-------+-------+\n"); + } + for (int j = 0; j < 9; j++) { + if (j % 3 == 0) { + printf("| "); + } + printf("%d ", sudoku[i][j]); // 输出数组中的元素 + } + printf("|\n"); + } + printf("+-------+-------+-------+\n"); +} +int main() { + // 初始化随机数生成器 + srand(time(0)); + + int grid[9][9] = {0}; // 创建3x9的数组并初始化为0 + + int numbers[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; // 创建包含数字1到9的数组 + + // 随机排列数组中的数字 + shuffle(numbers, 9); + + int row, col; + int numIndex = 0; + + // 将打乱顺序的数字填充到数组中 + for (row = 0; row < 3; row++) + { + int aa=0,bb=0,cc=0; + while(aa==bb||bb==cc||aa==cc) + { + aa=rand()%9; + bb= rand()%9; + cc=rand()%9; + } + grid[row][aa] = numbers[numIndex]; + numIndex++; + grid[row][bb] = numbers[numIndex]; + numIndex++; + grid[row][cc] = numbers[numIndex]; + numIndex++; + } + // 随机排列数组中的数字 + shuffle(numbers, 9); + + numIndex = 0; + + // 将打乱顺序的数字填充到数组中 + for (row = 3; row < 6; row++) + { + int aa=0,bb=0,cc=0; + while(aa==bb||bb==cc||aa==cc) + { + aa=rand()%9; + bb= rand()%9; + cc=rand()%9; + } + grid[row][aa] = numbers[numIndex]; + numIndex++; + grid[row][bb] = numbers[numIndex]; + numIndex++; + grid[row][cc] = numbers[numIndex]; + numIndex++; + } + // 随机排列数组中的数字 + shuffle(numbers, 9); + + +numIndex = 0; + + // 将打乱顺序的数字填充到数组中 + for (row = 6; row < 9; row++) + { + int aa=0,bb=0,cc=0; + while(aa==bb||bb==cc||aa==cc) + { + aa=rand()%9; + bb= rand()%9; + cc=rand()%9; + } + grid[row][aa] = numbers[numIndex]; + numIndex++; + grid[row][bb] = numbers[numIndex]; + numIndex++; + grid[row][cc] = numbers[numIndex]; + numIndex++; + } + // 打印数组 + printSudoku(grid); + + return 0; +} + +