本文介绍了从Smalltalk中的集合中生成所有组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我看到C#和其他语言可以解决此问题,而Smalltalk却无法解决。我有3个收藏集,例如:
I've seen this problem resolved for C# and other languages but not for Smalltalk. I have 3 collections, for example:
a := #(3 4 5).
b := #(4 1 2).
c := #(5 2 3).
我需要进行所有可能的组合,即e。:
and I need to make all possible combinations, i. e.:
#(3 4 5)
#(3 4 2)
#(3 4 3)
#(3 1 5)
#(3 1 2)
#(3 1 3)
#(3 2 5)
#(3 2 2)
#(3 2 3)
#(4 4 5)
...
我在Squeak和Pharo中看到过组合:atATimeDo:但是在这种情况下,我不知道如何使用它。这不是功课。有帮助吗?
I have seen in Squeak and Pharo there is combinations:atATimeDo: but I don't get how to use it for this case. This is not homework. Any help?
推荐答案
这是Smalltalk / X的类库(在SequentialCollection中)的代码。
请参阅最后的示例使用注释。
here is the code from Smalltalk/X's class library (in SequentialCollection).See the example-use comments at the end.
combinationsDo: aBlock
"Repeatly evaluate aBlock with all combinations of elements from the receivers elements.
The receivers elements must be collections of the individuals to be taken for the combinations"
self combinationsStartingAt:1 prefix:#() do:aBlock
combinationsStartingAt:anInteger prefix:prefix do:aBlock
"a helper for combinationsDo:"
|loopedElement|
loopedElement := self at:anInteger.
anInteger == self size ifTrue:[
loopedElement do:[:el | aBlock value:(prefix copyWith:el)].
^ self.
].
loopedElement do:[:el |
|newPrefix|
newPrefix := (prefix copyWith:el).
self combinationsStartingAt:anInteger+1 prefix:newPrefix do:aBlock
].
"
(Array
with:($a to:$d)
with:(1 to: 4))
combinationsDo:[:eachCombination | Transcript showCR: eachCombination]
"
"
(Array
with:#(1 2 3 4 5 6 7 8 9)
with:#(A))
combinationsDo:[:eachCombination | Transcript showCR: eachCombination]
"
"
#( (3 4 5)
(4 1 2)
(5 2 3)
) combinationsDo:[:eachCombination | Transcript showCR: eachCombination]
"
这篇关于从Smalltalk中的集合中生成所有组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!