続: n 番目の組み合わせ

ループを排除して、心持ち、すっきりとさせてみました。心持ち。w

SequenceableCollection >> combinations: digits atATimeAt: target
   | size sum ranges cursor digit |
   size _ self size.
   (size < digits or: [digits < 1]) ifTrue: [^ self species new].
   ranges _ OrderedCollection new.
   (size - 1 to: digits - 1 by: -1) 
      inject: 0 into:  [: lastIndex : n | ranges add: lastIndex + (n take: digits - 1)].
   cursor _ ranges findFirst: [: lastIndex | lastIndex >= target].
   sum _ cursor > 1 ifTrue: [ranges at: cursor - 1] ifFalse: [0].
   digit _ self species with: (self at: cursor).
   ^ digit, ((self allButFirst: cursor) combinations: digits - 1 atATimeAt: target - sum)