0

我想知道,我有一组包含我自己的数据类型的数组。看起来像:

traces = {[<label1>, <label2>], [<label1>], [<label1>,<label2>,<label3>]}

现在,我想要一个方法来清除集合中所有“前缀”现有的数组,所以我的新集合将在这个例子中:

traces = {[<label1>,<label2>,<label3>]} 

有人知道如何对此进行干净的实施吗?我希望有一个比单步执行跟踪和 Set new_traces 并多次比较每个数组项更简洁的解决方案。

注意:我定义 Array A 是 Array B 的前缀,如果 Array B 的第一项实际上是 Array A

4

2 回答 2

2

不是最快的解决方案,但相当简单:

s = Set.new([[1,2],[1],[1,2,3]])
s.reject{|prefix|
  s.any?{|array|
    array.length > prefix.length && array[0,prefix.length] == prefix
  }
}
#=>[[1, 2, 3]]
于 2011-04-12T14:11:59.060 回答
0

调用 flatten 然后 uniq

 class T
  attr_accessor :n
  def initialize(n); @n = n; end
  def eql?(other); n.eql?(other.n); end
  def hash; n.hash; end
end

a = [T.new(1), T.new(2), T.new(3), T.new(4), T.new(2), T.new(1), [T.new(2), T.new(2)], [T.new(4)]]

a.flatten.uniq.map(&:n) # => [1, 2, 3, 4]
于 2011-04-12T13:19:24.390 回答