Collections 组合:atATimeDo:Pharo5.0中的怪异行为
我想使用以下代码段在Pharo中生成组合:Collections 组合:atATimeDo:Pharo5.0中的怪异行为,collections,combinations,smalltalk,pharo,Collections,Combinations,Smalltalk,Pharo,我想使用以下代码段在Pharo中生成组合: | col | col := Set new. (0 to: 7) asArray combinations: 5 atATimeDo: [ : combination | col add: combination ]. ^ col 我不知道我做错了什么,但总是导致同一系列的重复: "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
| col |
col := Set new.
(0 to: 7) asArray
combinations: 5
atATimeDo: [ : combination | col add: combination ].
^ col
我不知道我做错了什么,但总是导致同一系列的重复:
"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))"
可能是什么问题?我认为这是因为性能原因,但是
#combines:atATimeDo:
的实现方式是创建一个组合大小的单个数组,并使用不同的元素填充它,然后将其传递给块。这更有效,因为您不必每次都分配一个新数组。另一方面,在你的例子中发生的事情是,你实际上在一次又一次地将同一个对象添加到你的集合中,但同时它发生了变化,因此你有了一个集合,这个集合中的同一个对象的状态是最后的组合。只需存储阵列的副本
,即可使代码正常工作:
| col |
col := Set new.
(0 to: 7) asArray
combinations: 5
atATimeDo: [ : combination | col add: combination copy ].
^ col