【问题标题】:Combinaison ruby Array multidimensionnel to get a Array two dimensional组合 ruby​​ Array multidimensionnel 以获得二维数组
【发布时间】:2015-10-23 09:37:37
【问题描述】:

我有一个多维数组,例如:

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

如何获取同一数组中除组合外的每个元素的组合:[1, 1],[1, 4],[2, 3]

我想得到:

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

谢谢。

【问题讨论】:

  • 为什么最后有 [2,3] 而没有 [1,4] ?你试过了吗?
  • @radubogdan,如果iji<jaarr[i]b 在@ 中,大概应该包括[a,b] 987654330@ 其中arr 是给定的数组数组。道格。对吗?
  • Doug,当你给出一个例子时,将每个输入对象分配给一个变量是有帮助的;例如,arr = [[1,1,...]。这样,读者可以在答案和 cmets 中引用arr,而无需定义它。
  • 返回的数组不应该包含[2,2]吗?如果是,请编辑;如果不是,请编辑解释原因。

标签: arrays ruby


【解决方案1】:

简短的回答是:

[[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]]

一步一步

  1. step1 = [[1, 1, 4], [2],[2, 3]].combination(2) 
    # => [[[1, 1, 4], [2]], [[1, 1, 4], [2, 3]], [[2], [2, 3]]]
    
  2. 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]]
    
  3. result = step2.uniq
    # => [[1, 2], [4, 2], [1, 3], [4, 3], [2, 2], [2, 3]]
    

更新

为了获得完全的独特性,您可以使用:

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

【讨论】:

  • 如果我有:[[1, 1, 4], [2],[2, 3, 4]].combination(2).map {|x,y| x.product(y)}.flatten(1).sort.uniq, 我得到 [[1, 2], [1, 3], [1, 4], [2, 2], [2, 3], [2, 4], [4, 2], [4, 3], [4, 4]],所以 [2, 4] 和 [4, 2] 不是 uniq
  • 检查我的更新。下次请详细说明您想要什么
  • 谢谢,我也明白了。
【解决方案2】:
arr = [[1, 1, 4], [2], [2, 3]]

a = arr.map(&:uniq)
(arr.size-1).times.flat_map { |i| arr[i].product(arr[i+1..-1].flatten.uniq)}.uniq
  #=> [[1,2],[1,3],[4,2],[4,3],[2,2],[2,3]]

这是使用我定义的here 方法Array#difference 的另一种方式:

arr.flatten.combination(2).to_a.difference(arr.flat_map { |a| a.combination(2).to_a }).uniq

Array#difference 类似于Array#-。以下示例说明了差异:

a = [1,2,3,4,3,2,2,4]
b = [2,3,4,4,4]

a     -      b #=> [1]
a.difference b #=> [1, 3, 2, 2]

【讨论】:

    猜你喜欢
    • 2013-03-29
    • 1970-01-01
    • 1970-01-01
    • 2012-08-14
    • 2011-04-30
    • 2021-02-23
    • 1970-01-01
    • 2017-02-11
    • 1970-01-01
    相关资源
    最近更新 更多