来自微信群发来的问题:
2 ,3,4,6怎么能算出24来,谁能想出4种来?
当然我就小动手了一下:
首先获取所有数字排列方式, 原理就是每个位置和其他位置都不重复
float poolBase[] = {4,6,2,3};
float pool[4];
int count =0;
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
if(j==i)continue;
for(int m=0;m<4;m++){
if(m==i||m==j)continue;
for(int n=0;n<4;n++){
if(n==i||n==j||n==m)continue;
pool[0] = poolBase[i];
pool[1] = poolBase[j];
pool[2] = poolBase[m];
pool[3] = poolBase[n];
// printf("%.0f%.0f%.0f%.0f\n",pool[i],pool[j],pool[m],pool[n]);
然后遍历各种算法组合并计算是否得到24
const char* pool2[]={"+","-","*","/"};
int pos[]={0,0,0};
while (true) {
if (pos[0]>=3 && pos[1]>=3 && pos[2]>=3) {
break;
}
stringstream ss;
float sum = pool[0];
ss<<pool[0];
for (int x=0; x<3; x++) {
ss<<pool2[pos[x]];
switch (pos[x]) {
case 0:
sum+=pool[x+1];
break;
case 1:
sum-=pool[x+1];
break;
case 2:
sum*=pool[x+1];
break;
case 3:
sum/=pool[x+1];
break;
default:
break;
}
ss<<pool[x+1];
}
pos[2]+=1;
if (pos[2]>3) {
pos[1]+=1;
pos[2]=0;
if (pos[1]>3) {
pos[0]+=1;
pos[1]=0;
}
}
if (sum==24) {
count++;
printf("24 = %s \n",ss.str().c_str());
}
}
再把上面遍历的排序放置进检测可能组合的算法中:
得到了18种组合
24 = 4+6-2*3
24 = 4-2+6*3
24 = 4/2+6*3
24 = 4+2*3+6
24 = 6+4-2*3
24 = 6-2+4*3
24 = 6*2-4*3
24 = 6/2+3*4
24 = 6-3*4*2
24 = 6*3+4+2
24 = 6-3*2*4
24 = 6*3+2+4
24 = 2+4*3+6
24 = 2*6-4*3
24 = 3*6+4+2
24 = 3*6+2+4
24 = 3-2*4*6
24 = 3-2*6*4
count = 18