[Newbies] Another extension proposal -> subsets

cdrick cdrick65 at gmail.com
Wed Jul 23 15:51:50 UTC 2008

When we don't find method, we reinvent the wheel. Ok, so this is what
happened with my quest on rounding float. So here is another example.
I needed a method subsets ... to have all subsets of a Set...

#(1 2 ) asSet subsets " -> a Set(a Set(1 2) a Set(1) a Set(2) a Set()) "

Is there already something ? I couldn't find so here is what I did ?
probably hackish (because of the binary mask) so feel free to comment

| subsetsSize subsets workArray |
	workArray := self asArray.
 	subsetsSize := 2 raisedTo: self size.
	subsets := OrderedCollection new.
	1 to: subsetsSize do: [:ea |
		subsets add: ((workArray masquedBy: (ea printStringBase: 2))
asSet)]. "masque par une conversion binaire"
	^subsets asSet  "could be an array of sets"

ArrayedCollection>>masquedBy: aBitString
| result entry bitString |
	entry := self reverse.
	bitString := aBitString reverse.
	result := OrderedCollection new.
	1 to: (self size) do: [:ea |
		 ((bitString  at: ea ifAbsent: []) = $1) ifTrue: [result add: (entry
at: ea)]].
	^result reverse


More information about the Beginners mailing list