Groovy 二维数组组合

发布于 2025-01-19 00:03:08 字数 156 浏览 6 评论 0原文

我有一个2D数组,看起来像[[1,2,3],[10,11]]。我想获得下一个组合:[[1,2,3,10],[1,2,3,11]]。这个想法是从左数组中获取所有值,并将其与右数组中的每个值结合。我尝试过开箱即用的方法(例如Compinations(),置换()获得预期的结果,但没有任何成功。请帮忙。

I have a 2D array which looks like [[1, 2, 3], [10, 11]]. I want to get the next combinations: [[1, 2, 3, 10], [1, 2, 3, 11]]. The idea is to take all values from left array and combine it with each value from right array. I've tried different Groovy out of the box methods like combinations(), permutations() to get the expected result, but without any success. Please, help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦中楼上月下 2025-01-26 00:03:08

为什么不简单:

def a = [[1, 2, 3], [10, 11]]

def res = a[ 1 ].collect{ a[ 0 ] + it }

assert res == [[1, 2, 3, 10], [1, 2, 3, 11]]

Why not simply:

def a = [[1, 2, 3], [10, 11]]

def res = a[ 1 ].collect{ a[ 0 ] + it }

assert res == [[1, 2, 3, 10], [1, 2, 3, 11]]
深空失忆 2025-01-26 00:03:08

如果有人可以作弊...将第一个列表嵌套到另一个列表中可以让我们仍然使用 .combinations()

def a = [[[1, 2, 3]], [10, 11]] //a[0] changed to [a[0]]
a.combinations().collect{it.flatten()} //[[1, 2, 3, 10], [1, 2, 3, 11]]

现在,如果您无法像那样存储值,您仍然可以使更改部分代码。所有这些都假设该列表只是一对。

([a[0]] + a[1..<(a.size())]).combinations().collect{it.flatten()} //same result

我相信有更少的非正统方法可以做到这一点,但这是一个快速而肮脏的解决方案。

If one can cheat... Nesting the first list into another list can let us use .combinations() still:

def a = [[[1, 2, 3]], [10, 11]] //a[0] changed to [a[0]]
a.combinations().collect{it.flatten()} //[[1, 2, 3, 10], [1, 2, 3, 11]]

Now, if you can't store the values like that, you can still still make the change part of your code. All this assumes that the list is just a pair.

([a[0]] + a[1..<(a.size())]).combinations().collect{it.flatten()} //same result

I believe there are less unorthodox ways of doing it, but that's a quick and dirty solution.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文