C# 通过数组循环到笛卡尔幂n
我想循环遍历数组,数组的结果是笛卡尔幂n 这就是我想要实现的,仅使用n个深度:C# 通过数组循环到笛卡尔幂n,c#,arrays,cartesian-product,C#,Arrays,Cartesian Product,我想循环遍历数组,数组的结果是笛卡尔幂n 这就是我想要实现的,仅使用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中,这
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#中实现这一点
任何帮助都将不胜感激。谢谢。您可以通过一点数学和
收益率来实现笛卡尔积:
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;
}
}
生成以下输出:
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
您可以计算两个数组的笛卡尔积,如下所示
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);
您可以尝试递归解决方案。Enumerable.Repeat(array,n).Aggregate((IEnumerable)new[]{new int[0]},(a,b)=>a.SelectMany(c=>b,(d,e)=>{var f=new int[d.Length+1];d.CopyTo(f,0);f[d.Length]=e;return f;})
。这并不能回答问题。这不是关于找到两个数组的笛卡尔积,而是关于找到任意数量数组的积。
var cartesionProduct = CartesianProduct (set1,set2);