小算法:获得一个数的所有可能性组合

来自微信群发来的问题:

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

这里写图片描述

整个群都不说话了, 不知道为啥

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值