C# 单词重复排列,其中单词被多次使用
我试图从一组单词中生成一个组合列表 我一直在使用生成组合C# 单词重复排列,其中单词被多次使用,c#,permutation,C#,Permutation,我试图从一组单词中生成一个组合列表 我一直在使用生成组合 var words = File.ReadAllLines(@"C:\words.txt"); var allCombinations = new List<string>(); var combis = new Combinations<string>(words, 3, GenerateOption.WithRepetition); allCombinations.AddRange(combis.Select
var words = File.ReadAllLines(@"C:\words.txt");
var allCombinations = new List<string>();
var combis = new Combinations<string>(words, 3, GenerateOption.WithRepetition);
allCombinations.AddRange(combis.Select(c => c.Aggregate((j, k) => j + "-" + k)));
等等
但我缺少一个单词被多次使用的组合
"Word1-Word2-Word1"
"Word1-Word3-Word1"
"Word2-Word1-Word2"
如何获得多次使用单词的单词组合?您的情况基本上类似于在基数3中计数:
0 0 0
0 0 1
0 0 2
0 1 0
0 1 1
0 1 2
0 2 0
// and so on..
如果您使用的库没有实现所需的逻辑,您可以自己实现它。以下是想法:
public static IEnumerable<string> Permutate(string[] words)
{
// 0 0 0
int[] indices = new int[words.Length];
// yield 0 0 0
yield return string.Join("-", indicies.Select(x => words[x]));
// moves to 0 0 1 and so on, returns false after 3 3 3
while (CountStep(indicies))
{
// yield next permutation
yield return string.Join("-", indicies.Select(x => words[x]));
}
}
公共静态IEnumerable置换(字符串[]字)
{
// 0 0 0
int[]索引=新的int[words.Length];
//产量0
返回字符串。Join(“-”,indicies.Select(x=>words[x]);
//移动到0 0 1,依此类推,在3之后返回false
while(CountStep(指示))
{
//产生下一个置换
返回字符串。Join(“-”,indicies.Select(x=>words[x]);
}
}
实施CountStep也不难:
public static bool CountStep(int[] arr)
{
// assumes we count in base N for an N sized array
var maxDigit = arr.Length - 1;
for (var i = arr.Length - 1; i >= 0; i--)
{
if (arr[i] < maxDigit)
{
arr[i]++;
for (var j = i + 1; j < arr.Length; j++)
{
arr[j] = 0;
}
return true;
}
}
return false;
}
publicstaticboolcountstep(int[]arr)
{
//假设我们以N为基数计算N大小的数组
var maxDigit=阵列长度-1;
对于(变量i=阵列长度-1;i>=0;i--)
{
if(arr[i]
public static bool CountStep(int[] arr)
{
// assumes we count in base N for an N sized array
var maxDigit = arr.Length - 1;
for (var i = arr.Length - 1; i >= 0; i--)
{
if (arr[i] < maxDigit)
{
arr[i]++;
for (var j = i + 1; j < arr.Length; j++)
{
arr[j] = 0;
}
return true;
}
}
return false;
}