【发布时间】:2021-03-14 01:37:12
【问题描述】:
我在教程点上在线找到了这段代码。链接https://www.tutorialspoint.com/cplusplus-program-to-generate-all-possible-combinations-out-of-a-b-c-d-e。
我试图考虑如何修改它,以便它从生成的列表中随机选择一个组合,但我还没有弄清楚。
#include<iostream>
using namespace std;
void Combi(char a[], int reqLen, int s, int currLen, bool check[], int l)
{
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);
check[s] = false;
Combi(a, reqLen, s + 1, currLen, check, l);
}
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;
}
【问题讨论】:
-
为什么看起来像是数学作业。
-
我们通常不会为您做作业。
-
如果您还是随机获取解决方案,为什么不直接选择 4 个随机数并跳过昂贵的组合步骤?
-
这“5个事件”是如何涉及的?
标签: c++