Created
November 16, 2016 18:04
-
-
Save mandeluna/c2f694dcbf2baabec3506439d98ed1e6 to your computer and use it in GitHub Desktop.
Combinations of n items taken k at a time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"Return a list of all the combinations of a list of tokens taken k items at a time" | |
| combinations choices | | |
combinations := [:tokens :k | | |
(k <= 0) ifTrue: [OrderedCollection new] ifFalse: [ | |
((tokens size == 0) or: [k == tokens size]) | |
ifTrue: [OrderedCollection with: tokens] | |
ifFalse: [ | |
choices := combinations value: (tokens copyFrom: 2 to: tokens size) value: k-1. | |
choices := (choices isEmpty | |
ifTrue: [choices add: (OrderedCollection with: tokens first); yourself] | |
ifFalse: [choices collect: [:choice | | |
(OrderedCollection with: tokens first) | |
addAll: choice; | |
yourself]]) | |
addAll: (combinations value: (tokens copyFrom: 2 to: tokens size) value: k); | |
yourself]]]. | |
^combinations value: #(a b c d e f) asOrderedCollection value: 4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment