C ++
 Computer >> コンピューター >  >> プログラミング >> C ++

各サブセットに正確にk個の要素を持つすべての可能なサブセットを生成するC++プログラム


これは、各サブセットに正確にk個の要素を持つすべての可能なサブセットを生成するC++プログラムです。

アルゴリズム

Begin
   function PossibleSubSet(char a[], int reqLen, int s, int currLen, bool check[], int l):
   If currLen > reqLen
   Return
   Else if currLen = reqLen
      Then print the new generated sequence.
   If s = l
      Then return no further element is left.
      For every index there are two options:
         either proceed with a start as ‘true’ and recursively call PossibleSubSet()
         with incremented value of ‘currLen’ and ‘s’.
         Or proceed with a start as ‘false’ and recursively call PossibleSubSet()
         with only incremented value of ‘s’.
End

#include<iostream>
using namespace std;
void PossibleSubSet(char a[], int reqLen, int s, int currLen, bool check[], int l)
//print the all possible combination of given array set
{
   if(currLen > reqLen)
   return;
   else if (currLen == reqLen) {
      cout<<"\t";
      for (int i = 0; i < l; i++) {
         if (check[i] == true) {
            cout<<a[i]<<" ";
         }
      }
      cout<<"\n";
      return;
   }
   if (s == l) {
      return;
   }
   check[s] = true;
   PossibleSubSet(a, reqLen, s + 1, currLen + 1, check, l);
   //recursively call PossibleSubSet() with incremented value of ‘currLen’ and ‘s’.
   check[s] = false;
   PossibleSubSet(a, reqLen, s + 1, currLen, check, l);
   //recursively call PossibleSubSet() with only incremented value of ‘s’.
}
int main() {
   int i,n,m;
   bool check[n];
   cout<<"Enter the number of elements: ";
   cin>>n;
   char a[n];
   cout<<"\n";
   for(i = 0; i < n; i++) {
      cout<<"Enter "<<i+1<<" element: ";
      cin>>a[i];
      check[i] = false;
   }
   cout<<"\nEnter the length of the subsets required: ";
   cin>>m;
   cout<<"\nThe possible combination of length "<<m<<" for the given array set:\n";
   PossibleSubSet(a, m, 0, 0, check, n);
   return 0;
}

出力

Enter the number of elements: 7
Enter 1 element: 7
Enter 2 element: 6
Enter 3 element: 5
Enter 4 element: 4
Enter 5 element: 3
Enter 6 element: 2
Enter 7 element: 1
Enter the length of the subsets required: 6
The possible combination of length 6 for the given array set:
7 6 5 4 3 2
7 6 5 4 3 1
7 6 5 4 2 1
7 6 5 3 2 1
7 6 4 3 2 1
7 5 4 3 2 1
6 5 4 3 2 1

  1. 配列要素の乗算のためのC++プログラム

    整数要素の配列で与えられ、タスクは配列の要素を乗算して表示することです。 例 Input-: arr[]={1,2,3,4,5,6,7} Output-: 1 x 2 x 3 x 4 x 5 x 6 x 7 = 5040 Input-: arr[]={3, 4,6, 2, 7, 8, 4} Output-: 3 x 4 x 6 x 2 x 7 x 8 x 4 = 32256 以下のプログラムで使用されるアプローチは次のとおりです − 一時変数を初期化して、最終結果を1で格納します ループを0からnまで開始します。nは配列のサイズです 最終結果を得るには、tempの値にarr[i]を掛け続

  2. 辞書式順序で特定のセットのすべてのサブセットを生成するC++プログラム

    これは、辞書式順序で特定のセットのすべてのサブセットを生成するC++プログラムです。このアルゴリズムは、指定された配列のセットからの各長さの可能なすべての組み合わせを昇順で出力します。このアルゴリズムの時間計算量はO(n *(2 ^ n))です。 アルゴリズム Begin    For each length ‘i’ GenAllSubset() function is called:    1) In GenAllSubset(), if currLen is more than the reqLen then return.