我正在尝试实现在问题C# Permutation of an array of arraylists?中找到的解决方案之一。
它应该执行笛卡尔积,但它返回正确数量的列表,但是每个列表始终只是每个数组的第一个。 以下是代码和结果。
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace TestCartProd
{
class MainClass
{
public static void Main (string[] args)
{
string[][] myList = new string[3][];
myList[0] = new string[] { "1", "5", "3", "9" };
myList[1] = new string[] { "2", "3" };
myList[2] = new string[] { "a", "93" };
List<IEnumerable<string>> v = GetPermutations (myList).ToList();
foreach (IEnumerable t in v) {
foreach (string u in t) {
Console.Write (u);
}
Console.WriteLine ();
}
}
public static IEnumerable<IEnumerable<T>> GetPermutations<T>(IEnumerable<IEnumerable<T>> lists)
{
// Check against an empty list.
if (!lists.Any())
{
yield break;
}
// Create a list of iterators into each of the sub-lists.
List<IEnumerator<T>> iterators = new List<IEnumerator<T>>();
foreach (var list in lists)
{
var it = list.GetEnumerator();
// Ensure empty sub-lists are excluded.
if (!it.MoveNext())
{
continue;
}
iterators.Add(it);
}
bool done = false;
while (!done)
{
// Return the current state of all the iterator, this permutation.
yield return from it in iterators select it.Current;
// Move to the next permutation.
bool recurse = false;
var mainIt = iterators.GetEnumerator();
mainIt.MoveNext(); // Move to the first, succeeds; the main list is not empty.
do
{
recurse = false;
var subIt = mainIt.Current;
if (!subIt.MoveNext())
{
subIt.Reset(); // Note the sub-list must be a reset-able IEnumerable!
subIt.MoveNext(); // Move to the first, succeeds; each sub-list is not empty.
if (!mainIt.MoveNext())
{
done = true;
}
else
{
recurse = true;
}
}
}
while (recurse);
}
}
}
}
结果: 12a 12a 12a 12a 12a 12a 12a 12a 12a 12a 12a 12a 12a 12a 12a 12a
翻译:Results代表结果,12a为具体的数据。以上示例为重复出现的数据。