如何获得具有不同数量元素的n个数组的所有可能组合?

编程入门 行业动态 更新时间:2024-10-08 00:31:09
本文介绍了如何获得具有不同数量元素的n个数组的所有可能组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一些在编程时未知的数组,也许是3或4或7 ...每个数组都有一些元素,即

I have some number of arrays which is unknown at programming time, maybe it is 3 or 4 or 7 ... each array has some elements, i.e,

a={1 2 3 4} b={6 7 5 2 1} c={22 4 6 8 4 8 5 4} d={....} e, f, g, ...

我想得到通过从每个数组中采样一个数字来获得所有可能的组合,例如,一种情况是我从a拾取 1,从b拾取 7,从c拾取第一个 8,d [3],e [5]。 ..制成 1,7,8,d [3],e [5],...。无法使用嵌套的for循环,因为我不知道编译时的数组数量。如果已知例如4个数组(a,b,c,d),我可以使用4个循环:

I want to get get all possible combinations by sampling one number from each array for example one case is that I pick up "1" from a, "7" from b, first "8" from c, d[3], e[5],... to make "1,7,8,d[3],e[5],...". It's not possible to use nested for loops because I don't know the number of arrays at compile time. If it was known for example 4 arrays (a,b,c,d) I could use 4 loops:

for (int i = 0; i <= a.Length-1; i++) { for (int j = 0; i <= b.Length-1; j++) { for (int k = 0; i <= c.Length-1; k++) { for (int m = 0; i <= d.Length-1; m++) { Response[f++] = a[i].toString()+","+b[j].toString()+","+c[k].toString()+","+d[m].toString(); } } } }

但对于不同数量的数组,我不知道。

but for different number of arrays, I don't have any idea.

推荐答案

这可行:

Func< IEnumerable<IEnumerable<int>>, IEnumerable<IEnumerable<int>>> f0 = null; f0 = xss => { if (!xss.Any()) { return new [] { Enumerable.Empty<int>() }; } else { var query = from x in xss.First() from y in f0(xss.Skip(1)) select new [] { x }.Concat(y); return query; } }; Func<IEnumerable<IEnumerable<int>>, IEnumerable<string>> f = xss => f0(xss).Select(xs => String.Join(",", xs));

因此,如果我输入以下内容:

So if I have this input:

var input = new [] { new [] { 1, 2, 3, 4, }, new [] { 6, 7, 5, 2, 1, }, new [] { 22, 4, 6, 8, 4, 8, 5, 4, }, };

我可以这样获得结果:

var results = f(input);

以下是根据注释中的请求简单汇总结果的版本:

Here's a version which simply sums the results, as per the request in the comments:

Func<IEnumerable<IEnumerable<int>>, IEnumerable<int>> f = null; f = xss => { if (!xss.Any()) { return new [] { 0 }; } else { var query = from x in xss.First() from y in f(xss.Skip(1)) select x + y; return query; } }; var input = new [] { new [] { 1, 2, 3, 4, }, new [] { 6, 7, 5, 2, 1, }, new [] { 22, 4, 6, 8, 4, 8, 5, 4, }, }; var results = f(input);

更多推荐

如何获得具有不同数量元素的n个数组的所有可能组合?

本文发布于:2023-11-30 12:38:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649992.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   数组   如何获得   元素   数量

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!