我有5个文本文件,其中包含一些元素。
A:
内的内容示例9864902,9864892,9864891,9864890,9864889,9864888,9864887,9864886,9864885,9864884,9864883,9864882,9864881,9864880,9864879,9864878,9864877,9864876,9864873,9864872,9864870,9864869,9864868,9864867,9864866,9864865,9864864,9864863,9864862,9864861,9864858,9864857,9864856,9864855,9864854,9864853,9864852,9864851,9864850,9864849,9864848,9864847,9864846,9864845,9864844,9864843,9864842,9864841,9864840,9864839,9864838,9864837,9864836,9864835,9864834,9864833,9864832,9864831,9864830,9864829,9864828,9864827,9864826,9864825,9864824,9864823,9864822,9864821,9864820,9864819,9864818,9864817,9864816,9864815,9864814,9864813,9864812,9864811,9864810,9864809,9864808,9864807,9864806,9864805,9864804,9864803,9864802,9864801,9864800,9864799,9864798,9864797,9864796,9864795,9864794,9864793,9864792,9864791,9864790,9864789,9864788,9864787,9864786,9864785,9864784,9864783,9864782,9864781,9864780,9864779,9864778,9864777,9864776,9864775,9864774,9864773,9864772,9864771,9864770,9864769,9864768,9864767,9864766,9864765,9864764,9864763,9864762,9864761
(还有更多,大约18k,但现在我只希望获得第1000名。)
这是在文本文件中获取内容的方法之一。
public string getA(int index)
{
// Contains 1000 elements
string[] Array_A = File.ReadAllLines("D:\\user\\A.txt");
string[] A = null;
for (int i = 0; i < Array_A.Length; i++)
{
A = Array_A[i].Split(',');
}
return A[index].ToString();
}
其他方法与上述相同。只需将“A”更改为其他名称即可。
现在我想编写另一种方法来获取组合文本文件中所有元素的元素。
public string[] UniqueCombination(int number)
{
// Write the code here
}
例如,UniqueCombination(7),我需要获得7种独特的组合。
A(0)B(0)C(0)D(0)E(0)
A(0)B(0)C(0)D(1)E(0)
A(0)B(0)C(1)D(0)E(0)
A(0)B(0)C(1)D(1)E(0)
A(0)B(0)C(2)D(0)E(0)
A(0)B(0)C(2)D(1)E(0)
A(0)B(3)C(0)D(0)E(0)
(上面是组合的例子,因为E只有1个元素,所以总是返回第一个位置元素。)
然而,对于这种情况,我想获得数千,可能达到5位数(20,000)的组合。怎么做?我已经为随机索引编写了另一种方法。但对于这种情况我不知道。
(p.s元素的顺序无关紧要,只是承诺每个组合都是唯一的)
答案 0 :(得分:2)
int size = 7;
// read the text and create lists for each file
var listA = ReadFileToList("D:\\user\\A.txt");
var listB = ReadFileToList("D:\\user\\B.txt");
var listC = ReadFileToList("D:\\user\\C.txt");
var listD = ReadFileToList("D:\\user\\D.txt");
// get the combinations from lists
var combinations = (from a in listA
from b in listB
from c in listC
from d in listD
select new[] { a, b, c, d })
.Take(size)
.ToList();
如果您需要随机选择项目
var randomCombinations = (from a in listA
from b in listB
from c in listC
from d in listD
select new[] { a, b, c, d })
.OrderBy(n => Guid.NewGuid())
.Take(size)
.ToList();
您需要如下方式的辅助方法
public List<string> ReadFileToList(string path)
{
List<string> temp = new List<string>();
using (StreamReader r = new StreamReader(path))
{
string line;
if ((line = r.ReadLine()) != null)
{
temp =line.Split(',').ToList();
}
}
return temp;
}
您可以打印结果如下
Console.WriteLine(string.Join("|",
randomCombinations.Select(c => string.Join(",", c))));
结果将显示如下
A,D,E,G|A,D,F,G|B,D,F,G|B,C,E,G|A,C,E,G|A,C,F,G|B,C,F,G
OR扩展您的代码如下
foreach (var item in combinations) { Console.WriteLine(string.Join(",", item)); }