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

与えられた数のリストのすべての可能な組み合わせを生成するC++プログラム


これは、特定の数値リストの可能なすべての組み合わせを生成するC++プログラムです

アルゴリズム

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

#include<iostream>
using namespace std;
void Combi(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;
   Combi(a, reqLen, s + 1, currLen + 1, check, l);
      //recursively call Combi() with incremented value of ‘currLen’ and ‘s’.
   check[s] = false;
   Combi(a, reqLen, s + 1, currLen, check, l);
      // recursively call Combi() with only incremented value of ‘s’.
}
int main() {
   int i,n;
   bool check[n];
   cout<<"Enter the number of element array have: ";
   cin>>n;
   char a[n];
   cout<<"\n";
   for(i = 0; i < n; i++) {
      cout<<"Enter "<<i+1<<" element: ";
      cin>>a[i];
      check[i] = false;
   }
   for(i = 1; i <= n; i++) {
      cout<<"\nThe all possible combination of length "<<i<<" for the given array set:\n";
      Combi(a, i, 0, 0, check, n);
   }
   return 0;
}

出力

Enter the number of element array have: 4
Enter 1 element: 4
Enter 2 element: 3
Enter 3 element: 2
Enter 4 element: 1
The all possible combination of length 1 for the given array set:
4
3
2
1
The all possible combination of length 2 for the given array set:
4 3
4 2
4 1
3 2
3 1
2 1
The all possible combination of length 3 for the given array set:
4 3 2
4 3 1
4 2 1
3 2 1
The all possible combination of length 4 for the given array set:
4 3 2 1
>
  1. リスト内のすべての数値を乗算するC#プログラム

    まず、リストを設定します- List<int> myList = new List<int> () {    5,    10,    7 }; ここで、変数の値を1に設定すると、乗算に役立ちます- int prod = 1; ループして製品を入手する- foreach(int i in myList) {    prod = prod*i; } 以下はコードです- 例 using System; using System.Collections.Generic; public cl

  2. Pythonで特定の文字列の文字のすべての可能な組み合わせのリストを見つけるプログラム

    文字列sがあるとします。 sの文字の可能なすべての組み合わせを見つける必要があります。同じ文字セットを持つ2つの文字列がある場合は、辞書式順序で最も小さい文字列を表示します。そして、1つの制約は、sの各文字が一意であるということです。 したがって、入力がs =pqrのような場合、出力は[r、qr、q、pr、pqr、pq、p] これを解決するには、次の手順に従います- st_arr:=新しいリスト s-1から0の範囲サイズのiの場合、1ずつ減らします。 範囲0からst_arr-1のサイズのjの場合、do st_arrの最後に(s [i] concatenate st_arr [j]