Example Program: SETS (Advanced) |
Top Previous Next |
This program shows how boolean operators are used to operate on sets. A single integer can represent a set containing up to 16 elements. The elements are either present or absent, as indicated by set or cleared bits (1 or 0).
The elements that are common to two or more sets are determined by "anding" the sets using the boolean "&" operator. These common elements are called the "intersection" of the sets. Similarly, the "union" of the sets is determined by the "!" operator.
\SETS.XPL code ChOut=8, CrLf=9, Text=12; int Week, Work, Free; \Sets of days int Day; def \Day\ Mon=1, Tue=2, Wed=4, Thr=8, Fri=$10, Sat=$20, Sun=$40; \Assign days of the week to the individual bits of an integer
proc Show(SET); \Graphically show the set of days int Set, Day; begin Day:= Mon; while Day & Week do \For all of the days of the week do: begin if Day & SET then ChOut(0, ^X) else ChOut(0, ^-); Day:= Day * 2; \Next day--shift bit left end; CrLf(0); end; \Show
begin \Main \Initialize work days and free days to empty sets: Work:= 0; Free:= 0; \There are 7 days in a week, so set the first 7 bits: Week:= $7F; \Saturday and Sunday are free days: Day:= Sat; Free:= Day ! Free ! Sun; Show(Free); \The rest of the week are work days: Work:= Week & ~Free; Show(Work); \Free is a subset of Week:p; \Free is a subset of Week: if (Free & Week) = Free then ChOut(0, ^O); \Week is a superset of Work: if (Week & Work) = Work then ChOut(0, ^K); \Work and Free are mutually exclusive: if ~(Work & Free) then Text(0, " PETER?"); \We won't work on Sunday! if Sun & Work then Text(0, " FORGET IT!"); CrLf(0); end; \Main
This program produces the following output:
-----XX XXXXX-- OK PETER? |