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.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
# include <stdio.h>
# include <time.h>
# include <stdlib.h>
//任务二: 随机生成一个9*9的不完整数组
int main ( )
{
srand ( time ( NULL ) ) ;
//Step1:创造一个9*9的零矩阵
int m [ 9 ] [ 9 ] = { 0 } ;
//Step2:我们对矩阵的1-3,4-6,7-9行处理
//我们定义一个数组a[3][9]={1,2,...,9;0,0,0...,0} , a[1][i]即指i+1在1-3中的行数 , a[2][i]即指i+1所在的列数
int a [ 3 ] [ 9 ] = { 0 } ;
for ( int i = 0 ; i < 9 ; i + + )
{
a [ 0 ] [ i ] = i + 1 ;
}
int judge = 1 ; //judge表示分三批处理的批次
while ( judge < = 3 )
{
//Step2-1: 随机生成行数
for ( int i = 0 ; i < 9 ; i + + )
{
a [ 1 ] [ i ] = rand ( ) % 3 + 1 ; //生成一个 1-3的随机数
if ( i > = 3 ) //检查是否一行里面超过了3个数
{
int times [ 3 ] = { 0 } ; //times[1]即指2在前i个数中出现的次数
for ( int j = 0 ; j < = i ; j + + )
{
times [ a [ 1 ] [ j ] - 1 ] + + ;
}
if ( times [ 0 ] > 3 | | times [ 1 ] > 3 | | times [ 2 ] > 3 )
{
i = i - 1 ; //一行里面超过了3个数, 则对于数i+1, 我们重新生成其所在行数;
}
}
}
//Step2-2: 随机生成列数
for ( int i = 0 ; i < 9 ; i + + )
{
a [ 2 ] [ i ] = rand ( ) % 9 + 1 ; //生成1-9的随机数
if ( i > 0 )
{
//检查是否对于在同一行的数,其列数重复
m [ a [ 1 ] [ i - 1 ] - 1 + 3 * ( judge - 1 ) ] [ a [ 2 ] [ i - 1 ] - 1 ] = i ; //把数i填入最初创建的矩阵m
if ( m [ a [ 1 ] [ i ] - 1 + 3 * ( judge - 1 ) ] [ a [ 2 ] [ i ] - 1 ] ! = 0 ) //如果不为0, 说明数的位置上重合
{
i = i - 1 ; //则对于数i+1, 我们重新生成其所在列数;
}
}
}
m [ a [ 1 ] [ 8 ] - 1 + 3 * ( judge - 1 ) ] [ a [ 2 ] [ 8 ] - 1 ] = 9 ;
judge + + ;
}
//Step3:输出随机数组
for ( int i = 0 ; i < 9 ; i + + )
{
printf ( " | " ) ; //每一行的以|开始
for ( int j = 0 ; j < 9 ; j + + )
{
printf ( " %d " , m [ i ] [ j ] ) ;
if ( ( j + 1 ) % 3 = = 0 )
{
printf ( " | " ) ; //区分3*3
if ( j = = 8 )
{
printf ( " \n " ) ;
}
}
}
if ( ( i + 1 ) % 3 = = 0 & & i ! = 8 )
{
printf ( " |----分割---| \n " ) ;
} //每三行就换一行
}
}