我想要找到一个数组中每个数组元素的交集,然后取这个交集。
输入是数组的数组,例如,"'list_arrays‘如下面的脚本所述“'filter’是需要对观察到的交叉点的总长度应用的限制输出应为这样的数组"[2,4]”
list_arrays = [[1, 2, 3, 4], [2, 5, 6], [1, 5, 8], [8, 2, 4]]
filter = 2
first_element_array = Array.new
list_arrays.each_with_index do |each_array1, index1|
list_arrays.each_with_index do |each_array2, index2|
unless index1 < index2
intersection = each_array1 & each_array2
if intersection.length == filter.to_i
first_element_array.push(intersection)
end
end
end
end
puts first_element_array上面的过程需要很长的执行时间,因为我有太长的数组(百万行)。我需要一个简单的方法来处理这个问题。有谁有什么简单的想法吗?
发布于 2013-02-28 22:54:13
破译你的代码看起来你要求的是“如果一个集合的对组合有一定的大小(在这个例子中是2),那么返回这个交集之间的交集”。我会写(函数式方法):
list_arrays = [[1, 2, 3, 4], [2, 5, 6], [1, 5, 8], [8, 2, 4]]
list_arrays.combination(2).map do |xs, ys|
zs = xs & ys
zs.size == 2 ? zs : nil
end.compact
#=> [[2, 4]]建议的优化: 1)使用集合,2)使用自定义抽象Enumerable#map_compact (相当于map+compact,但它会动态丢弃nil,自己编写)。3)过滤掉不满足谓词的子数组:
require 'set'
xss = list_arrays.select { |xs| xs.size >= 2 }.map(&:to_set)
xss.combination(2).map_compact do |xs, ys|
zs = xs & ys
zs.size == 2 ? zs : nil
end
#=> [#<Set: {2, 4}>]https://stackoverflow.com/questions/15138400
复制相似问题