我想循环遍历数组,该数组是笛卡尔幂n的数组结果。 https://en.wikipedia.org/wiki/Cartesian_product#n-ary_product
这就是我想要达到的目标,只有n深度:
int[] array = new int[] { 5, -4, ... }
foreach(int a in array) {
foreach(int b in array) {
foreach(int c in array) {
...
int[] NewArray = new int[] { a, b, c, ... }
在Python中,这相当于:
from itertools import product
for (NewArray in product(array, repeat=n)):
print(NewArray)
我不知道如何在C#中实现这一点。
任何帮助都将受到高度赞赏。感谢。
答案 0 :(得分:0)
您可以使用一点点数学和yield return
:
static public IEnumerable<T[]> Product<T>(IList<T> items, int repeat) {
var total = (int)Math.Pow(items.Count, repeat);
var res = new T[repeat];
for (var i = 0 ; i != total ; i++) {
var n = i;
for (var j = repeat-1 ; j >= 0 ; j--) {
res[j] = items[n % items.Count];
n /= items.Count;
}
yield return res;
}
}
像这样调用
foreach (var arr in Product(new[] {"quick", "brown", "fox"}, 3)) {
Console.WriteLine(string.Join("-", arr));
}
产生以下输出:
quick-quick-quick
quick-quick-brown
quick-quick-fox
quick-brown-quick
quick-brown-brown
quick-brown-fox
quick-fox-quick
quick-fox-brown
quick-fox-fox
brown-quick-quick
brown-quick-brown
brown-quick-fox
brown-brown-quick
brown-brown-brown
brown-brown-fox
brown-fox-quick
brown-fox-brown
brown-fox-fox
fox-quick-quick
fox-quick-brown
fox-quick-fox
fox-brown-quick
fox-brown-brown
fox-brown-fox
fox-fox-quick
fox-fox-brown
fox-fox-fox
答案 1 :(得分:-1)
你可以计算两个数组的笛卡尔积,如下所示
string[][] CartesianProduct(string[] arr1, string[] arr2)
{
// for each s1 in arr1, extract arr2,
// then pass s1 and s2 into a newly-made string array.
return arr1.SelectMany(s1 => arr2, (s1, s2) => new string[] { s1, s2 })
.ToArray();
}
假设你有两个阵列即
string[] set1 = new string[] { "a", "b", "c" };
string[] set2 = new string[] { "x", "y", "z" };
调用CartesianProduct函数,该函数将返回结果值,如下所示。
var cartesionProduct = CartesianProduct (set1,set2);