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.
10-29/suiji.c

67 lines
1.3 KiB

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void swap(int *a,int *b){//交换函数
int temp;
temp=*a;
*a=*b;
*b=temp;
}
void shuffle(int *array,int size){ //随机交换
int i;
int j;
srand(time(NULL));
for(i=size-1;i>0;i--){
j=rand()%(i+1);
swap(&array[i],&array[j]);
}
}
void fillBoard(int board[9][9])
{
int arr[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int positions[9];//位置 从0到8
int i,j;
for (i=0;i<9;i++)
{
positions[i]=i;
}
//每三行
for (i=0;i<9;i+= 3)
{
shuffle(arr,9);//随机0-9 随机位置
shuffle(positions,9);
for (j = 0; j < 3; j++)
{//每三行填充
board[i][positions[j]] = arr[j];
board[i+1][positions[j+3]] = arr[j+3];
board[i+2][positions[j+6]] = arr[j+6];
}
}
}
void print(int board[9][9]){//格式化输出函数
printf("|-----------------------|\n");
int i=0,j=0,s=0,k=0;
for(i=0;i<9;++i){
for(j=0;j<9;j++){
while(j%3==0){
printf("| ");
break;
}
printf("%d ",board[i][j]);
}
printf("|\n");
while((i+1)%3==0){
printf("|-----------------------|\n");
break;
}
}
}
int main(){
int board[9][9]={0};//初始化
fillBoard(board);
print(board);
return 0;
}