For some reason the following code produce a set with duplicate values.
I'm not sure how uniqueness of an array in ruby is defined so maybe this is somehow expectable?
require 'set'
xs = [1, 2, 3]
xss = Set.new []
xs.each do |x|
xss.merge xss.to_a.map{|xs| xs.push x}
xss.add [x]
p xss
end
will prints
#<Set: {[1]}>
#<Set: {[1, 2], [1, 2], [2]}>
#<Set: {[1, 2, 3, 3], [1, 2, 3, 3], [2, 3], [1, 2, 3, 3], [2, 3], [3]}>
What's wrong?
EDIT
change xs.push x
to xs + [x]
will fix it.
You are effectively altering the objects within the set, which is not allowed.
From the documentation:
Set assumes that the identity of each element does not change while it is stored. Modifying an element of a set will render the set to an unreliable state.
Regarding your comment
I want
#<Set: {[1], [1, 2], [2], [1, 3], [1, 2, 3], [2, 3], [3]}>
You could use Array#combination
:
a = [1, 2, 3]
(1..a.size).flat_map { |n| a.combination(n).to_a }
#=> [[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With