gpt4 book ai didi

ruby - 将数组中的每个数组相交 - Ruby

转载 作者:太空宇宙 更新时间:2023-11-03 17:24:55 25 4
gpt4 key购买 nike

我想找到数组中每个数组元素的交集并取交集。

输入是数组的数组,例如,“下面这个脚本中提到的‘list_arrays’”“过滤器”是需要应用于观察到的交叉路口总长度的限制输出预计为这样的数组“[[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

由于我的数组太长(以百万行计),因此上述过程需要很长时间执行。我需要一个简单的 rubistic 方法来处理这个问题。有人对此有任何简单的想法吗?

最佳答案

破译您的代码似乎您要求的是“如果交集具有特定大小(示例中为 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}>]

关于ruby - 将数组中的每个数组相交 - Ruby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15138400/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com