如何从List<string>
来源生成所有单词组合的列表?
例如,我有一个10,600多个单词的List<string>
,我需要将其转换为List<List<string>>
,但是,子列表只需要包含最多包含给定最大长度的组合,对于这个例子,我会说3。
我不关心单词出现在子列表中的顺序。例如,我只需要列表中的以下一项:
"laptop", "computer", "reviews"
"laptop", "reviews", "computer"
"computer", "laptop", "reviews"
"computer" "reviews", "laptop"
"reviews", "computer", "laptop"
"reviews", "laptop", "computer"
是否可以根据我需要生成的大量组合来实现?
非常感谢任何帮助。
答案 0 :(得分:6)
首先,我不确定你是否真的想要生成如此庞大的列表。如果你真的这样做,那么我建议你考虑使用iterators生成懒惰列表而不是这个巨大的列表:
static void Main()
{
var words = new List<string> {"w1", "w2", "w3", "w4", "w5", "w6", "w7"};
foreach (var list in Generate(words, 3))
{
Console.WriteLine(string.Join(", ", list));
}
}
static IEnumerable<List<string>> Generate(List<string> words, int length, int ix = 0, int[] indexes = null)
{
indexes = indexes ?? Enumerable.Range(0, length).ToArray();
if (ix > 0)
yield return indexes.Take(ix).Select(x => words[x]).ToList();
if (ix > length)
yield break;
if (ix == length)
{
yield return indexes.Select(x => words[x]).ToList();
}
else
{
for (int jx = ix > 0 ? indexes[ix-1]+1 : 0; jx < words.Count; jx++)
{
indexes[ix] = jx;
foreach (var list in Generate(words, length, ix + 1, indexes))
yield return list;
}
}
}
答案 1 :(得分:0)
希望我没有弄乱任何东西。
for(int i = 0; i < list.Count; i ++)
{
list1 = new List<string> { list[i] };
listcombinations.Add(list1);
for(int j = i + 1; j < list.Count; j ++)
{
list1 = new List<string> { list[i], list[j] };
listcombinations.Add(list1);
for(int k = j + 1; k < list.Count; k ++)
{
list1 = new List<string> { list[i], list[j], list[k] };
listcombinations.Add(list1);
}
}
}
答案 2 :(得分:0)
我认为问题主要是检查列表中是否已存在单词组合:
你可以做些什么:
//generate a dictionary with key hashcode / value list of string
Dictionary<int, List<string>> validCombinations= new Dictionary<int, List<string>>();
//generating anyway your combinations (looping through the words)
List<string> combinationToCheck = new List<string>(){"reviews", "laptop", "computer"};
//sort the words
combinationToCheck.Sort();
string combined = String.Join("", combinationToCheck.ToArray());
//calculate a hash
int hashCode = combined.GetHashCode();
//add the combination if the same hash doesnt exist yet
if(!validCombinations.ContainsKey(hashCode))
validCombinations.Add(hashCode, combinationToCheck);
答案 3 :(得分:0)
private List<List<string>> GetCombinations()
{
List<List<string>> mResult= new List<List<string>>();
for (int i = 0; i < mList.Count; i++)
{
for (int k = 0; k < mList.Count; k++)
{
if (i == k) continue;
List<string> tmpList = new List<string>();
tmpList.Add(mList[i]);
int mCount = 1;
int j = k;
while (true)
{
if (j >= mList.Count) j = 0;
if (i != j)
{
tmpList.Add(mList[j]);
mCount++;
}
j += 1;
if (mCount >= mList.Count) break;
}
mResult.Add(tmpList);
}
}
return mResult;
}