我正在尝试从一组单词生成一个组合列表。
我一直在使用http://www.codeproject.com/Articles/26050/Permutations-Combinations-and-Variations-using-C-G来生成组合
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)));
给出3个单词“Word1”,“Word2”和“Word3”我得到了像
这样的组合列表"Word1-Word1-Word1"
"Word1-Word1-Word2"
"Word1-Word1-Word3"
等
但是我错过了多次使用单词的组合
"Word1-Word2-Word1"
"Word1-Word3-Word1"
"Word2-Word1-Word2"
如何获得多次使用单词的单词组合?
答案 0 :(得分:1)
你的情况基本上就像在基数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]));
}
}
实现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;
}