Reputation: 937
I want to generate combinations in Pharo using the following snippet:
| col |
col := Set new.
(0 to: 7) asArray
combinations: 5
atATimeDo: [ : combination | col add: combination ].
^ col
I don't know what I am doing wrong, but always results in repetitions of the same collection:
"a Set(#(7 7 7 7 7) #(7 7 7 7 7) #(7 7 7 7 7) #(7 7 7 7 7) #(7 7 7 7 7) #(7 7 7 7 7) #(7 7 7 7 7) #(7 7 7 7 7) #(7 7 7 7 7) #(7 7 7 7 7) #(7 7 7 7 7) #(7 7 7 7 7))"
What could be the problem?
Upvotes: 4
Views: 73
Reputation: 13396
I think that this is because of performance reasons, but the way #combinations:atATimeDo:
is implemented it creates a single array of the size of a combination and the populates it with different elements and passes it to the block. This is more efficient because you do not allocate a new array each time. On the other hand what happens in your case is that you are actually adding that same object to your set over and over again but in a meantime it changes, so as the result you have a set with the same object which has a state of the last combination. You can make your code work by simply storing a copy
of the array:
| col |
col := Set new.
(0 to: 7) asArray
combinations: 5
atATimeDo: [ : combination | col add: combination copy ].
^ col
Upvotes: 5