圆圈处不重复的填入1至9,使得每条边的四个数字相加的总和相等。
求解思路:
数组中存放1到9的数字,每次随机交换两个数字,构建出新的数字组合,计算这个数字组合是否符合要求。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
void swap(int *a, int *b)
{
int t = *a;
*a = *b;
*b = t;
}
int main()
{
int data[9] = {
1, 2, 3, 4, 5, 6, 7, 8, 9
};
int i, j;
int a, b, c;
/* 通过系统时间来初始化随机数发生器 */
srand(time(NULL));
/* 尝试交换若干次 */
for(i = 0; i < 10000; i++)
{
/* 将索引0与索引1~8的数字进行交换 */
j = 1 + rand() % 8;
swap(&data[0], &data[j]);
/* 计算当前组合,如果符合条件则打印出来 */
a = (data[0] + data[1] + data[2] + data[3]);
b = (data[3] + data[4] + data[5] + data[6]);
c = (data[6] + data[7] + data[8] + data[0]);
if (a == b && b == c)
{
for(j = 0; j < 9; j++)
{
printf("%d,", data[j]);
}
printf("\n");
}
}
return 0;
}
使用w64devkit gcc编译器编译运行,得出一些求解结果。
PS D:\Codes> gcc -o test test.c
PS D:\Codes> .\test
8,2,4,7,6,5,3,9,1,
1,6,8,5,4,2,9,7,3,
5,8,6,1,7,3,9,4,2,
7,6,5,3,1,9,8,2,4,
3,7,2,9,5,1,6,4,8,
3,7,2,9,5,1,6,4,8,
8,1,9,3,5,6,7,4,2,
9,7,3,1,6,8,5,2,4,
7,2,6,4,5,9,1,3,8,
7,1,8,3,9,5,2,4,6,
9,3,4,7,6,2,8,5,1,
7,8,1,3,5,9,2,6,4,
6,2,7,5,3,8,4,1,9,
3,8,1,7,6,4,2,9,5,
3,8,1,7,6,4,2,9,5,
5,4,2,9,3,7,1,8,6,
2,6,7,5,3,4,8,9,1,
7,2,6,4,9,5,1,8,3,
3,2,9,7,1,5,8,6,4,
9,5,1,8,2,6,7,3,4,
7,8,1,3,5,9,2,6,4,
3,6,4,8,1,5,7,9,2,
9,3,4,7,2,6,8,5,1,
2,6,8,3,5,4,7,1,9,
9,5,1,8,6,2,7,3,4,
9,2,4,5,8,6,1,7,3,
4,9,5,1,3,8,7,6,2,
3,4,8,5,6,2,7,1,9,
8,1,9,2,7,6,5,3,4,
PS D:\Codes>
第一个结果: