Reputation: 345
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]]
or similiar. Maybe I should use the Set class for this? But maybe this can also be achieved with another method?
Upvotes: 2
Views: 1033
Reputation: 67900
At this moment all the answers use O(n log n) sort
as uniqueness function. A histogram (frequency counter) is 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.
Upvotes: 2
Reputation: 15294
[[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.
Upvotes: 10
Reputation: 8657
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]]
Upvotes: 0
Reputation: 8792
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
Upvotes: 2