【问题标题】:Nested Match & Sum In RubyRuby 中的嵌套匹配和求和
【发布时间】:2014-01-14 09:20:03
【问题描述】:

目前我有这个数组 =

[["abc", [0.0, 1.0, 2.0, 3.0], "Testing"], ["efg", [1.0, 2.0, 3.0, 4.0], "Testing"]] 

条件:

如果每个嵌套数组 index2 都相同,那么我想总结一下 [0.0 + 1.0, 1.0 + 2.0, 2.0 + 3.0, 3.0 + 4.0] = [1.0, 3.0, 5.0, 7.0]

我想要的最终结果: [["efg", [1.0, 3.0, 5.0, 7.0], "测试"]]

有什么方法或建议可以得到这个结果吗?

【问题讨论】:

  • 您尝试过什么解决方法?这是一个很简单的问题,你至少应该尝试自己做。

标签: ruby multidimensional-array


【解决方案1】:

我在 TDD 中构建它很开心:

def nested_match_sum(data)
  grouped = data.group_by(&:last)

  grouped.values.map do |array|
    array.inject(nil) do |result, elem|
      if result
        elem[1] = array_position_sum(elem[1], result[1])
      end

      elem
    end
  end

end

def array_position_sum(first, second)
  first.zip(second).map do |couple|
    couple.first + couple.last
  end
end

require 'rspec/autorun'

describe "#nested_match_sum" do
  let(:data) do
    [
      ["abc", [0.0, 1.0, 2.0, 3.0], "Testing"],
      ["efg", [1.0, 2.0, 3.0, 4.0], "Testing"]
    ]
  end

  it "groups by last element and aggregates the sum" do
    expect(nested_match_sum(data)).to eq(
      [["efg", [1.0, 3.0, 5.0, 7.0], "Testing"]]
    )
  end

  context "giving multiple keys" do
    let(:data) do
      [
        ["abc", [0.0, 1.0, 2.0, 3.0], "Testing"],
        ["efg", [1.0, 2.0, 3.0, 4.0], "Testing"],
        ["abc", [0.0, 1.0, 2.0, 3.0], "Another"],
        ["ghj", [2.0, 3.0, 4.0, 5.0], "Another"]
      ]
    end

    it "works aswell" do
      expect(nested_match_sum(data)).to eq([
        ["efg", [1.0, 3.0, 5.0, 7.0], "Testing"],
        ["ghj", [2.0, 4.0, 6.0, 8.0], "Another"]
      ])
    end
  end
end

describe "#array_position_sum" do
  let(:first) { [1, 2, 3] }
  let(:second) { [4, 5, 6] }

  it "sums two arrays by position" do
    expect(array_position_sum(first, second)).to eq(
      [5, 7, 9]
    )
  end
end

【讨论】:

  • 它的工作真棒!感谢帮助!我理解你给出的代码。
猜你喜欢
  • 2021-11-16
  • 2022-01-11
  • 2013-11-28
  • 1970-01-01
  • 2021-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-06
相关资源
最近更新 更多