我将输入作为 int 并根据该输入我想要两个字符的组合, 例如 我将输入作为 2 并且我有两个字符 x 和 y 所以我想要这样的组合
xx,yy,xy,yx
如果输入是3,我要
xxx,xyy,xxy,xyx,yxx,yyy,yxy.yyx
等等,我已经尝试了下面的代码,
int input1 = 4;
Double totalpossibilities = Math.Pow(2, input1);
string[] PArray = new string[Convert.ToInt16(totalpossibilities)];
char[] chars = new char[] { 'x', 'y'};
for (int i = 0; i < totalpossibilities; i++)
{
string possibility = "" ;
for (int j = 0; j < input1; j++)
{
Random random = new Random();
int r = random.Next(chars.Length);
char randomChar = chars[r];
possibility = possibility + randomChar;
}
if (PArray.Contains(possibility))
{
i--;
}
else
PArray[i] = possibility;
}
但是正如你所看到的,我使用的是随机函数,所以我需要很长时间才能完成,是否有任何不同的逻辑?
最佳答案
使用从 here 中逐字复制的笛卡尔积扩展方法的副本:
static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences)
{
IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };
return sequences.Aggregate(
emptyProduct,
(accumulator, sequence) =>
from accseq in accumulator
from item in sequence
select accseq.Concat(new[] {item}));
}
然后在你的代码中你可以:
IEnumerable<char> possibleCharacters = "xy";//change to whatever
int numberOfDigits = 3;
var result = Enumerable.Repeat(possibleCharacters, numberOfDigits)
.CartesianProduct()
.Select(chars => new string(chars.ToArray()));
//display (or do whatever with) the results
foreach (var item in result)
{
Console.WriteLine(item);
}
关于c# - 两个字符的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10606277/