Skip to content

Instantly share code, notes, and snippets.

@mandeluna
Created November 16, 2016 18:04
Show Gist options
  • Save mandeluna/c2f694dcbf2baabec3506439d98ed1e6 to your computer and use it in GitHub Desktop.
Save mandeluna/c2f694dcbf2baabec3506439d98ed1e6 to your computer and use it in GitHub Desktop.
Combinations of n items taken k at a time
"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