【问题标题】:combinations:atATimeDo: weird behavior in Pharo 5.0组合:atATimeDo:Pharo 5.0 中的奇怪行为
【发布时间】:2016-09-16 15:47:08
【问题描述】:

我想使用以下 sn-p 在 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 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))"

可能是什么问题?

【问题讨论】:

    标签: collections combinations smalltalk pharo


    【解决方案1】:

    我认为这是出于性能原因,但#combinations:atATimeDo: 的实现方式会创建一个组合大小的单个数组,并用不同的元素填充它并将其传递给块。这更有效,因为您不会每次都分配一个新数组。另一方面,在您的情况下发生的情况是,您实际上是一遍又一遍地将同一个对象添加到您的集合中,但与此同时它会发生变化,因此您有一个具有相同对象的集合,其状态为最后的组合。您可以通过简单地存储数组的copy 来使您的代码工作:

    | col |
    col := Set new.
    (0 to: 7) asArray
        combinations: 5
        atATimeDo: [ : combination | col add: combination copy  ].
    ^ col
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-14
      • 2010-12-23
      • 1970-01-01
      • 2015-10-12
      • 2014-11-26
      • 1970-01-01
      • 2023-03-27
      • 2019-12-22
      相关资源
      最近更新 更多