1

Is there a class that represents an unordered array in Ruby? I cannot use array because:

[1,2] != [2,1]

And I cannot use set because I can only have unique elements. I want a kind of both combinations. A list that doesn't care about ordering and can have more than 1 of the same element.

4 Answers 4

4

It is called multiset. Here is Ruby implementation.

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

Comments

4

I guess you have extend the Array class and write your own == method. Here is my very experimental attempt:

class UnorderedArray < Array
  def ==(other)
    self_copy = self.sort
    other = other.sort
    self_copy == other
  end
end

a = UnorderedArray.new
a << 1 << 2
# [1, 2]

b = UnorderedArray.new
b << 2 << 1
# [2, 1]

a == b
# returns true

1 Comment

I think this is a better and easier idea rather than having a new gem
0

Here is a slightly cleaner mixin that will work on unsortable arrays and caches the hash value as it is O(n).

class UnorderedArray < Array
  def hash
    unless @o && @o == super.hash
      p = Hash.new(0)
      each{ |v| p[v] += 1 }
      @p = p.hash
      @o = super.hash
    end
    @p.hash
  end
  def <=>(b)
    raise "You can't order me"
  end
  def ==(b)
    hash == b.hash
  end
end

however #eql? will return false unless unless the arrays are in the same order.

Comments

0

One-liner:

Hash[a.zip(a.map{|x| a.count(x)})] == Hash[e.zip(e.map{|x| e.count(x)})]

Comments

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.