C# 生成一个数字的所有可能组合,而每个数字的范围不同
我已经在互联网上搜索了几天,但还没有找到适合我需要的好方法。所以我试着问一下 我在寻找一种方法来生成一个数字的所有可能的组合,而每个数字都有不同的范围 让我举个例子: 我的输入:[1-3],[0-9],[4],[2-3] 其中很少有组合是: 1042 1043 1142 1143 1242 等等C# 生成一个数字的所有可能组合,而每个数字的范围不同,c#,permutation,combinations,C#,Permutation,Combinations,我已经在互联网上搜索了几天,但还没有找到适合我需要的好方法。所以我试着问一下 我在寻找一种方法来生成一个数字的所有可能的组合,而每个数字都有不同的范围 让我举个例子: 我的输入:[1-3],[0-9],[4],[2-3] 其中很少有组合是: 1042 1043 1142 1143 1242 等等 代码不能在内存中存储某个变量的所有组合,因为我将处理大数字(最多10位)。该程序可以生成具有所有可能性的txt文件,并逐个写入它们,或者只在控制台中打印它们 输入的数字长度和每个数字的范围在给出之前是未
tnx您可以使用一种称为
这是C++中的一个例子。
#include <iostream>
#include <fstream>
#include <algorithm>
#include <numeric>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <deque>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cassert>
#include <cmath>
#include <complex>
#include <stack>
#include "time.h"
using namespace std;
template <typename T> string tostr(const T& t) { ostringstream os; os<<t; return os.str(); }
vector< pair< int, int > > ranges;
string cur;
void go(int at) {
if (at == (int)ranges.size()) {
// we're at the end of the ranges vector, print the number
cout<<cur<<endl;
return;
}
for(int i = ranges[at].first; i <= ranges[at].second; ++i) {
// add the digit for this range to the string
cur += tostr(i);
// recursive call
go(at+1);
// erase the last digit we added (this is where the backtracking part comes in)
cur.erase(cur.end()-1);
}
}
int main() {
ranges.push_back(make_pair(1,3));
ranges.push_back(make_pair(0,9));
ranges.push_back(make_pair(4,4));
ranges.push_back(make_pair(2,3));
cur = "";
go(0);
return 0;
}
尽管这是一个非常古老的问题,因为它被标记为
C
,但没有C#答案,这里是我的变体。它是非递归的,有助于在紧密循环中提高性能:
var minimums = new[] { 2, 0, 1, 7, 1 };
var maximums = new[] { 4, 6, 3, 9, 4 };
var current = minimums.ToArray();
while (true)
{
Console.WriteLine(string.Join("", current));
int pos = 0;
while (pos < maximums.Length)
{
current[pos]++;
if (current[pos] <= maximums[pos])
break;
current[pos] = minimums[pos];
pos++;
}
if (pos == maximums.Length)
break;
}
var最小值=new[]{2,0,1,7,1};
var最大值=新[]{4,6,3,9,4};
无功电流=最小值ToArray();
while(true)
{
Console.WriteLine(string.Join(“,current));
int pos=0;
而(位置<最大长度)
{
当前[pos]++;
如果(当前[pos]你能告诉我,你尝试了什么?你被困在哪里了?可能是完美的复制品!!我花了时间将它移植到c#但是它工作得完美无缺。tnx!@Urban48-不客气。我很高兴代码对你有帮助。
var minimums = new[] { 2, 0, 1, 7, 1 };
var maximums = new[] { 4, 6, 3, 9, 4 };
var current = minimums.ToArray();
while (true)
{
Console.WriteLine(string.Join("", current));
int pos = 0;
while (pos < maximums.Length)
{
current[pos]++;
if (current[pos] <= maximums[pos])
break;
current[pos] = minimums[pos];
pos++;
}
if (pos == maximums.Length)
break;
}