admin管理员组

文章数量:1558098


I have a 2D array as below

[[1, 4.0, "burger"], [1, 8.0, "tofu_log"], [2, 5.0, "burger"], [2, 6.5, "tofu_log"]]

Here, each element is a collection of restaurant_id, price and item. The task is to return unique restaurant_id, sum of prices, and the items such that the sum should be minimum. I want to get

[[1, 12.0, "burger, tofu_log"], [2, 11.5, "burger, tofu_log"]]

answer:

arr.group_by { |rest_id, _| rest_id }.map do |rest_id, items| 
  [rest_id, 
   items.map { |_, price| price }.inject(:+), 
   items.sort.map { |_, _, product| product }.join(", ") ]
end
# => [[1, 12.0, "burger, tofu_log"], [2, 11.5, "burger, tofu_log"]] 

本文标签: MERGINGBasedArraysummationuniqueness