一。方阵旋转
对一个方阵转置,就是把原来的行号变列号,原来的列号变行号
例如,如下的方阵:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
转置后变为:
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
但,如果是对该方阵顺时针旋转(不是转置),却是如下结果:
13 9 5 1
14 10 6 2
15 11 7 3
16 12 8 4
下面的代码实现的功能就是要把一个方阵顺时针旋转。
void rotate(int* x, int rank)
{
int* y = (int*)malloc( ______________); // 填空 sizeof(int)*16
for(int i=0; i<rank * rank; i++)
{
y[_________________________] = x[i]; // 填空
(i%rank)*rank+(rank-1-(i/rank))
}
for(i=0; i<rank*rank; i++)
{
x[i] = y[i];
}
free(y);
}
int main(int argc, char* argv[])
{
int x[4][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
int rank = 4;
rotate(&x[0][0], rank);
for(int i=0; i<rank; i++)
{
for(int j=0; j<rank; j++)
{
printf("%4d", x[i][j]);
}
printf("\n");
}
return 0;
}
二。割圆法
南北朝时,我国数学家祖冲之首先把圆周率值计算到小数点后六位,比欧洲早了1100年!他采用的是称为“割圆法”的算法,实际上已经蕴含着现代微积分的思想。
如图【1.jpg】所示,圆的内接正六边形周长与圆的周长近似。多边形的边越多,接近的越好!我们从正六边形开始割圆吧。
如图【2.jpg】所示,从圆心做弦的垂线,可把6边形分割为12边形。该12边形的边长a' 的计算方法很容易利用勾股定理给出。之后,再分割为正24边形,....如此循环会越来越接近圆周。
之所以从正六边开始,是因为此时边长与半径相等,便于计算。取半径值为1,开始割圆吧!
以下代码描述了割圆过程。
程序先输出了标准圆周率值,紧接着输出了不断分割过程中多边形边数和所对应的圆周率逼近值。
public class B21
{
public static void main(String[] args)
{
System.out.println("标准 " + Math.PI);
double a = 1;
int n = 6;
for(int i=0; i<10; i++)
{
double b = Math.sqrt(1-(a/2)*(a/2));
a = Math.sqrt((1-b)*(1-b) + (a/2)*(a/2));
n = ______________; //填空 2*n
System.out.println(n + " " + _______________); // 填空 a*n/2 圆周率即圆的周长与其直径之间的比率
}
}
}
三。放旗子
今有 6 x 6 的棋盘格。其中某些格子已经预先放好了棋子。现在要再放上去一些,使得:每行每列都正好有3颗棋子。我们希望推算出所有可能的放法。下面的代码就实现了这个功能。
初始数组中,“1”表示放有棋子,“0”表示空白。
int N = 0;
bool CheckStoneNum(int x[][6])
{
for(int k=0; k<6; k++)
{
int NumRow = 0;
int NumCol = 0;
for(int i=0; i<6; i++)
{
if(x[k][i]) NumRow++;
if(x[i][k]) NumCol++;
}
if(_____________________) return false; // 填空 NumRow!=3 || NumCol!=3
}
return true;
}
int GetRowStoneNum(int x[][6], int r)
{
int sum = 0;
for(int i=0; i<6; i++)
if(x[r][i]) sum++;
return sum;
}
int GetColStoneNum(int x[][6], int c)
{
int sum = 0;
for(int i=0; i<6; i++)
if(x[i][c]) sum++;
return sum;
}
void show(int x[][6])
{
for(int i=0; i<6; i++)
{
for(int j=0; j<6; j++)
printf("%2d", x[i][j]);
printf("\n");
}
printf("\n");
}
void f(int x[][6], int r, int c);
void GoNext(int x[][6], int r, int c)
{
if(c<6)
_______________________; // 填空 f(x, r, c+1)
else
f(x, r+1, 0);
}
void f(int x[][6], int r, int c)
{
if(r==6)
{
if(CheckStoneNum(x))
{
N++;
show(x);
}
return;
}
if(______________) // 已经放有了棋子 // 填空
x[r][c]==1
{
GoNext(x,r,c);
return;
}
int rr = GetRowStoneNum(x,r);
int cc = GetColStoneNum(x,c);
if(cc>=3) // 本列已满
GoNext(x,r,c);
else if(rr>=3) // 本行已满
f(x, r+1, 0);
else
{
x[r][c] = 1;
GoNext(x,r,c);
x[r][c] = 0;
if(!(3-rr >= 6-c || 3-cc >= 6-r)) // 本行或本列严重缺子,则本格不能空着!
GoNext(x,r,c);
}
}
int main(int argc, char* argv[])
{
int x[6][6] = {
{1,0,0,0,0,0},
{0,0,1,0,1,0},
{0,0,1,1,0,1},
{0,1,0,0,1,0},
{0,0,0,1,0,0},
{1,0,1,0,0,1}
};
f(x, 0, 0);
printf("%d\n", N);
return 0;
}
请分析代码逻辑,并推测划线处的代码。