2

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?

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

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

1 Comment

This will require recoding every time the sub-arrays change.
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 Comment

This is doing a uniq by hand when that abstraction is available in the core... the upper abstraction you can use, the better (more declarative, less verbose, usually faster).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.