【发布时间】:2018-07-06 16:57:31
【问题描述】:
我想遍历数组,它是数组到笛卡尔幂 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# 中实现这一点。
任何帮助将不胜感激。谢谢。
【问题讨论】:
-
你可以尝试递归解决。
-
Enumerable.Repeat(array, n).Aggregate((IEnumerable<int[]>)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; }))
标签: c# arrays cartesian-product