将数组的数组转换为数组的集合

时间:2021-11-25 20:22:03

I have an array of arrays and want to filter all arrays which have the same elements, which might only differ in their order.

我有一个数组,想要过滤所有元素相同的数组,它们的顺序可能不同。

[[1,0,1],[1,1,0],[2,3,5]] => [[1,0,1],[2,3,5]]

[[1,0,1],[1 1 0],[2、3、5]]= >[[1,0,1],[2、3、5]]

or similiar. Maybe I should use the Set class for this? But maybe this can also be achieved with another method?

或类似。也许我应该用集合类?但也许这也可以用另一种方法来实现?

4 个解决方案

#1


2  

At this moment all the answers use O(n log n) sort as uniqueness function. A histogram (frequency counter) is O(n):

此时,所有的答案都使用O(n log n)排序作为惟一函数。直方图(频率计数器)为O(n):

require 'facets/enumerable/frequency'
xss = [[1, 0, 1], [1, 1, 0], [2, 3, 5]]
xss.uniq(&:frequency)
#=> [[1, 0, 1], [2, 3, 5]]

Note however, that sort is a core optimized method and overall it will probably perform better.

但是请注意,这种排序是一种核心的优化方法,总的来说,它的性能可能会更好。

#2


10  

[[1,0,1],[1,1,0],[2,3,5]].uniq{|i| i.sort}

or

[[1,0,1],[1,1,0],[2,3,5]].uniq(&:sort)

Output:

输出:

[[1, 0, 1], [2, 3, 5]]

sort will make sure all sub-arrays are in the same order, and uniq gets rid of redundant items.

sort将确保所有子数组都按照相同的顺序排列,uniq将删除冗余项。

#3


2  

This should do it.

这应该这样做。

require 'set'

set = Set.new
set << [1,0,1].sort
set << [1,1,0].sort
set << [2,3,5].sort

set.each do |e|
  puts e.to_s
end

#4


0  

require 'set'

a = [[1,0,1],[1,1,0],[2,3,5]]

set = Set.new

a.map {|x| set << x.sort}
b = set.to_a

=> [[0, 1, 1], [2, 3, 5]]

#1


2  

At this moment all the answers use O(n log n) sort as uniqueness function. A histogram (frequency counter) is O(n):

此时,所有的答案都使用O(n log n)排序作为惟一函数。直方图(频率计数器)为O(n):

require 'facets/enumerable/frequency'
xss = [[1, 0, 1], [1, 1, 0], [2, 3, 5]]
xss.uniq(&:frequency)
#=> [[1, 0, 1], [2, 3, 5]]

Note however, that sort is a core optimized method and overall it will probably perform better.

但是请注意,这种排序是一种核心的优化方法,总的来说,它的性能可能会更好。

#2


10  

[[1,0,1],[1,1,0],[2,3,5]].uniq{|i| i.sort}

or

[[1,0,1],[1,1,0],[2,3,5]].uniq(&:sort)

Output:

输出:

[[1, 0, 1], [2, 3, 5]]

sort will make sure all sub-arrays are in the same order, and uniq gets rid of redundant items.

sort将确保所有子数组都按照相同的顺序排列,uniq将删除冗余项。

#3


2  

This should do it.

这应该这样做。

require 'set'

set = Set.new
set << [1,0,1].sort
set << [1,1,0].sort
set << [2,3,5].sort

set.each do |e|
  puts e.to_s
end

#4


0  

require 'set'

a = [[1,0,1],[1,1,0],[2,3,5]]

set = Set.new

a.map {|x| set << x.sort}
b = set.to_a

=> [[0, 1, 1], [2, 3, 5]]