用C++将1,2...9共9个数分成三组,分别组成三个三位数,且使这三个三位数构成1:2:3的比例

这需要用到排列组合算法

下面是我编写且能实现的代码

#include <iostream>
using namespace std;

class Permutation
{
public:
    void Perm(int a[],int k,int n);               //将数字进行全排列
    void PermOfThree(int a[]);                    //将数字分为3组,并为1:2:3的比例
private:
    int a[];
};


void Permutation::Perm(int a[],int k, int n)
{
    if(k<n-1)
    {
        for(int i=k;i<n;i++){                   //产生{a[k],···,a[n-1]}各种排列
            int t=a[k];
            a[k]=a[i];
            a[i]=t;
            Perm(a,k+1,n);                     //产生{a[k+1],···,a[n-1]}各种排列
            t=a[k];
            a[k]=a[i];
            a[i]=t;
        }

    }
    else{
        PermOfThree(a);
    }
}

void Permutation::PermOfThree(int a[])
       {
           double one = a[0]*100 + a[1]*10 + a[2];
           double two = a[3]*100 + a[4]*10 + a[5];
           double three = a[6]*100 + a[7]*10 + a[8];
           if( (two/one) == 2 && (three/one) == 3 )
           {
              cout<<one<<" "<<two<<" "<<three<<endl;
           }
       }



int main()
{
    int a[]={1,2,3,4,5,6,7,8,9};
    Permutation p;
    p.Perm(a,0,9);
    return 0;
}

这是运行的结果:

这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_24805141/article/details/51276481
今日推荐