第6章 指针
6.18.3 编写函数reverse_string, 函数原型为 void reverse_string(char *string);
#define NUL '\0'
void reverse_string(char *str)
{
char *tail = str;
char *head = str;
int len = 0;
for (; *tail++ != NUL;) len ++;
cout << len << endl;
for(int i = 0; i < len/2; i ++)
{
char tmp = *(str+i) ;
*(str+i) = *(str+len-i-1);
*(str+len-i-1) = tmp;
}
}
第7章 函数
7.11.1 递归编写Hermite Polynomials, 函数原型为 int hermite(int n, int x);
int hermite(int n, int x)
{
if(n <= 0) return 1;
if(n == 1) return 2*x;
return 2*x * hermite(n-1, x) - 2*(n-1) * hermite(n-2, x);
}
int ascii_to_integer(char *string)
{
int ans = 0;
while(*string != '\0')
ans = ans * 10 + (*string ++) - '0';
return ans;
}
第8章 数组
8.8.5 矩阵乘法, 函数原型 void matrix_multiply(int *m1, int *m2, int *r, int x, int y, int z);
void matrix_multiplication(int *m1, int *m2, int *r, int x, int y, int z)
{
for(int i = 0; i < x; i ++)
for(int j = 0; j < z; j ++)
for(int k = 0; k < y; k ++)
*(r+(i*z+j)) += (*(m1+(i*y+k))) * (*(m2+(k*z+j)));
for(int i = 0; i < x; i ++)
{
for(int j = 0; j < z; j ++)
cout << *(r+i*x+j) << " ";
cout << endl;
}
}
int main()
{
int a[][2] = {2, -6, 3, 5, 1, -1};
int b[][4] = {4, -2, -4, -5, -7, -3, 6, 7};
int c[3][4] = {0};
memset(c, 0, sizeof(c));
matrix_multiplication(&a[0][0], &b[0][0], &c[0][0], 3, 2, 4);
return 0;
}
const int N = 10;
bool mark[N][N];
int q[N][N];
int dir[8][2] = {1, 0, -1, 0, 0, 1, 0, -1, 1, 1, 1, -1, -1, -1, -1, 1};
bool safe(int row, int col)
{
memset(mark, false, sizeof(mark));
for(int i = 0; i < 8; i ++)
for(int j = 0; j < 8; j ++)
{
if(q[i][j]){
for(int k = 0; k < 8; k ++)
{
int tx = i + dir[k][0];
int ty = j + dir[k][1];
while(tx < 8 && ty < 8 && tx >= 0 && ty >= 0)
{
mark[tx][ty] = true;
tx += dir[k][0];
ty += dir[k][1];
}
}
}
}
return (!mark[row][col]);
}
void queen(int row, int col)
{
if(row == 7)
{
for(int i = 0; i < 8; i ++){
for(int j = 0; j < 8; j ++) cout << q[i][j];
cout << endl;
}
cout << "--------" << endl;
return ;
}
for(int i = 0; i < 8; i ++)
{
if(safe(row+1, i)){
q[row+1][i] = 1;
queen(row+1, i);
q[row+1][i] = 0;
}
}
}
int main()
{
for(int i = 0; i < 8; i ++)
{
q[0][i] = 1;
queen(0, i);
q[0][i] = 0;
}
return 0;
}