0

请看下面的代码

def test
  array = Array.new
  array2 = Array.new

  groups = [[424235, "goa", "italy"], [523436, "mumbai"], [342423, "africa", "goa"]]
  type = ["goa", "mumbai"]
  groups.each_with_index do |item,index|

       if item.include?(type[0]) == true
         array << index  << array2
        elsif item.include?(type[1]) == true
               array2 << index 
       else
         "nothing ;)"
       end

  end
  print array.each_slice(2).map { |a, b| [a, b.first] }
end
combine

#Output - [[0, 1], [2, 1]]

看到代码的问题了吗?那就是我正在使用一堆 if 和 else 语句。如果type数组有超过 2 个条目怎么办。我不能继续写 if 和 elsif 语句。这就是我需要你帮助的地方。什么是更好的构建代码的方法?循环?如果是这样的话。

4

1 回答 1

2

这是我的代码。

def combinations(groups, types)
  array = Array.new(types.size) { Array.new([]) }
  groups.each_with_index do |item, index|
     types.each_with_index { |type, i| array[i] << index if item.include? type }
  end

  flat = array.inject { |acc, i| acc.product i }.flatten
  flat.each_slice(types.size).to_a
end

示例测试用例

combinations([[424235, "goa", "italy"], [523436, "mumbai"], [342423, "africa", "goa"]], ["goa", "mumbai"])

输出 :[[0, 1], [2, 1]]

combinations([[424235, "goa", "italy"], [523436, "mumbai"], [342423, "africa", "goa"]], ["goa", "africa"])

输出 :[[0, 2], [2, 2]]

combinations([[424235, "goa", "italy"], [523436, "mumbai"], [342423, "africa", "goa"], [123, "india"]], ["goa", "mumbai", "india"])

输出 :[[0, 1, 3], [2, 1, 3]]

combinations([[424235, "goa", "italy"], [523436, "mumbai"], [342423, "mumbai", "goa"], [123, "india"]], ["goa", "mumbai", "india", "italy"])

输出 :[[0, 1, 3, 0], [0, 2, 3, 0], [2, 1, 3, 0], [2, 2, 3, 0]]

如果我正确理解了您的问题,那么这些应该是正确的。虽然我可能误会了你。如果我的问题错了,请告诉我,如果你能提供测试用例,那就太好了。

于 2013-02-17T13:15:49.673 回答