On Tue, Jul 28, 2009 at 03:21:38AM +0900, Marcin Grski wrote:
It would be nice to have for example {5, 1, 1, 1} in Set class object.
Is it possible? Which method should I use to add element in that way?
Sounds like you want a Bag, not a Set. I don’t know of aany
implementation but
it’s probably not hard to create one - all you have to do is keep track
of the
count of each element.
Sounds like you want a Bag, not a Set. I don’t know of aany
implementation but
it’s probably not hard to create one - all you have to do is keep track
of the
count of each element.
I’ve just read that elements in Set must be unique (because of Math). So
I’m going to solve my problem using arrays. Thanks for answer.
On Tue, Jul 28, 2009 at 03:21:38AM +0900, Marcin Grski wrote:
It would be nice to have for example {5, 1, 1, 1} in Set class object.
Is it possible? Which method should I use to add element in that way?
Sounds like you want a Bag, not a Set. I don’t know of aany implementation but
it’s probably not hard to create one - all you have to do is keep track of the
count of each element.
What about using a Hash mapping objects to counts? That way you can
still do efficient lookups whether something is contained in the Bag.
A simple implementation could look like this:
class Bag < Hash
def initialize(*contents)
super 0
contents.each {|item|
self[item] += 1
}
end
def each
return enum_for(__method__) unless block_given?
each_pair {|item, count|
count.times { yield item }
}
end
def to_a
each.to_a
end
Is their some reason that an Array doesn’t meet your needs? What does
Set
bring to the table that Array would be missing for you?
John
Well I need to compare arrays which contain digits (or letters in
another program). If I use set it is easy to compare two sets which have
the same, unique elements in random order for example 1233 and 3321
should be equal. If I use set I will get wrong result for 1332 and 2213
– it shouldn’t be equal. However, the array might contain elements with
the same value and it is what I neeed.
Solution is quite simple: I don’t need Set. If I sort arrays I can
compare them easily (for numbers). Thanks for Bag solutions, it’s quite
interesting and I may need it in future.
Thank you for your answers,
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.