Link to home
Start Free TrialLog in
Avatar of aloha
aloha

asked on

Manupulating Sets in Pascal

Is there a way to iterate through all the elements of a Set without using  a for loop that checks if every possible element is IN the Set ?
ASKER CERTIFIED SOLUTION
Avatar of julio011597
julio011597

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of d003303
d003303

Yo,
sure, again, it is possible. Just have a look at the memory structure:
(from Delphi help)
A set is a bit array where each bit indicates whether an element is in the set or not. The maximum number of elements in a set is 256, so a set never occupies more than 32 bytes. The number of bytes occupied by a particular set is calculated as

ByteSize = (Max div 8) - (Min div 8) + 1

where Min and Max are the lower and upper bounds of the base type of that set. The byte number of a specific element E is

ByteNumber = (E div 8) - (Min div 8)

and the bit number within that byte is

BitNumber = E mod 8

where E denotes the ordinal value of the element.

So you can take use of the memory structure. Construct a power set with bitwise algorithms and compare your set to the power set (PowerSet - MySet). If the result is [], all elements are in MySet.
Code will follow tomorrow, I have to search it on my wide-spread hard disk ;-)

Slash/d003303
And what if implementation changes??

In general, i believe that, when there's so much work to do for such a very common task, the _approach_ itself is - at least - suspicious.

Indeed, you end up discovering that any interesting approach, as d003303's, needs at least as much development efforts as switching to a straight array, with all the drawbacks related to: documenting, mantaining, and porting a code out of the ordinary.

This is not to say that one must never investigate an alternative approach... just be sure it is really worth doing.
My example consists of one procedure, CreatePowerSet, that creates a power set for each set you supply. If the implementation changes, you just need to change this procedure.
Borland uses the memory structure of sets heavily, because it resists on bit flags, and bit flags are most common through all platforms. The easiest example on how Borland uses them is (if you have D3 Pro) in .\Source\VCL\Toolwin.pas, method TToolWindow.WMNCPaint, Line 137.

Slash/d003303