从Smalltalk中的集合中生成所有组合

编程入门 行业动态 更新时间:2024-10-22 14:34:37
本文介绍了从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中的集合中生成所有组合

本文发布于:2023-11-29 00:38:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1644600.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   Smalltalk

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!