यह C++ प्रोग्राम दिए गए नंबरों की लिस्ट के सभी संभावित कॉम्बिनेशन (संयोजन) उत्पन्न करता है। यह पिछले आर्टिकल (ID: 1005082327) के समान है लेकिन विशेष रूप से नंबरों के लिए है।
एल्गोरिदम
शुरुआत
1. तत्वों की संख्या और तत्वों को इनपुट लें।
2. फंक्शन Combi():
- यदि currLen > reqLen तो लौटें
- अन्यथा यदि currLen == reqLen तो नई जनरेटेड सीक्वेंस प्रिंट करें
- यदि start == len तो लौटें
- प्रत्येक इंडेक्स के लिए दो विकल्प:
* check[start] = true के साथ Combi() को currLen+1, start+1 के साथ कॉल करें
* check[start] = false के साथ Combi() को केवल start+1 के साथ कॉल करें
समाप्ति
उदाहरण कोड
#include <iostream>
using namespace std;
void Combi(char a[], int reqLen, int start, int currLen, bool check[], int len) {
if (currLen > reqLen) return;
else if (currLen == reqLen) {
cout << "\t";
for (int i = 0; i < len; i++) {
if (check[i] == true)
cout << a[i] << " ";
}
cout << "\n";
return;
}
if (start == len) return;
check[start] = true;
Combi(a, reqLen, start + 1, currLen + 1, check, len);
check[start] = false;
Combi(a, reqLen, start + 1, currLen, check, len);
}
int main() {
int n;
cout << "Enter the number of elements in array: ";
cin >> n;
char a[n];
bool check[n];
cout << "\n";
for (int i = 0; i < n; i++) {
cout << "Enter " << i+1 << " element: ";
cin >> a[i];
check[i] = false;
}
for (int i = 1; i <= n; i++) {
cout << "\nAll possible combinations of length " << i << ":\n";
Combi(a, i, 0, 0, check, n);
}
return 0;
}
आउटपुट
Enter the number of elements in array: 4 Enter 1 element: 4 Enter 2 element: 3 Enter 3 element: 2 Enter 4 element: 1 All possible combinations of length 1: 4 3 2 1 All possible combinations of length 2: 4 3 4 2 4 1 3 2 3 1 2 1 All possible combinations of length 3: 4 3 2 4 3 1 4 2 1 3 2 1 All possible combinations of length 4: 4 3 2 1
कुल कॉम्बिनेशन: n तत्वों के लिए Σ C(n,k) = 2^n - 1 (k=1 से n तक)। n=4 के लिए: 4+6+4+1 = 15 कॉम्बिनेशन।
नोट: यह प्रोग्राम आर्टिकल 1005082327 के समान ही है। दोनों को मिलाकर एक व्यापक आर्टिकल बनाया जा सकता है।