Combinaison红宝石阵multidimensionnel得到一个数组二维 [英] Combinaison ruby Array multidimensionnel to get a Array two dimensional

查看:94
本文介绍了Combinaison红宝石阵multidimensionnel得到一个数组二维的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个阵列multidimensionnel喜欢的:

I have a Array multidimensionnel like:

[[1, 1, 4], [2],[2, 3]]

如何获得一个combinaison各元件除在同一阵列中combinaison:[1,1],[1,4],[2,3]

How to get a combinaison each element except the combinaison in the same array: [1, 1],[1, 4],[2, 3]

我想获得:

[1, 2],[1, 3],[4, 2],[4, 3],[2, 3]

感谢。

推荐答案

简短的回答是:

[[1, 1, 4], [2],[2, 3]].combination(2).flat_map {|x,y| x.product(y)}.uniq
# => [[1, 2], [4, 2], [1, 3], [4, 3], [2, 2], [2, 3]]


步步


step1 = [[1, 1, 4], [2],[2, 3]].combination(2) 
# => [[[1, 1, 4], [2]], [[1, 1, 4], [2, 3]], [[2], [2, 3]]]


  • step2 = step1.flat_map {|x,y| x.product(y)}
    # => [[1, 2], [1, 2], [4, 2], [1, 2], [1, 3], [1, 2], [1, 3], [4, 2], [4, 3], [2, 2], [2, 3]]
    


  • result = step2.uniq
    # => [[1, 2], [4, 2], [1, 3], [4, 3], [2, 2], [2, 3]]
    


  • 更新

    有关完整的独特性,你可以使用:

    For full uniqueness you could use:

    [[1, 1, 4], [2],[2, 3, 4]].combination(2).flat_map {|x,y| x.product(y)}.map(&:sort).uniq
    

    这篇关于Combinaison红宝石阵multidimensionnel得到一个数组二维的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆