/* * This set is abstract, except for toString() which can be applied * to any subclass. This is possible, because the abstract class * specifies sizeOf() and enumElements(), which yield the size and * contents of the set */ import cs101.terminal.*; abstract public class IntSet { // From the API abstract public void insert(int n); abstract public void delete(int n); abstract public boolean hasElement(int n); // Added because of our design abstract protected IntSet newEmptySet(); abstract protected List enumElements(); public boolean isEmpty() { // could be inefficient! return (sizeOf() == 0); } public int sizeOf() { // could be inefficient! if (enumElements() == null) return 0; else return enumElements().cardinality(); } /* * A helpful method to have around */ protected int getInt(List l) { return(((Integer) l.getThing()).intValue()); } public IntSet dup() { IntSet ans = newEmptySet(); ans.union(this); return(ans); } /* Because of our design, we can give implementations here * of the basic set operations. * These rely on enumElements though. There may be more efficient * ways of doing this, depending on the implementation */ public void union(IntSet s) { List other = s.enumElements(); List finger = other; while (finger != null) { int otherInt = getInt(finger); insert(otherInt); finger = finger.getRest(); } } public void intersection(IntSet s) { List finger = enumElements(); while (finger != null) { int coverInt = getInt(finger); if (!s.hasElement(coverInt)) delete(coverInt); finger = finger.getRest(); } } public void difference(IntSet s) { List other = s.enumElements(); List finger = other; while (finger != null) { int otherInt = getInt(finger); delete(otherInt); finger = finger.getRest(); } } public String toString() { return "Set of " + sizeOf() + " elements: " + enumElements(); } public void prt(String shouldHave) { Terminal.println("Should be {" + shouldHave + "}, actually have " + this); } public void selfTest() { IntSet n2 = newEmptySet(); IntSet n3 = newEmptySet(); insert(1); insert(0); prt("0, 1"); insert(0); prt("0, 1"); n2.insert(2); n2.insert(3); union(n2); prt("0, 1, 2, 3"); n2.prt("2, 3"); n3.insert(1); n3.insert(3); n3.insert(5); intersection(n3); n3.prt("1, 3, 5"); prt("1, 3"); insert(101); difference(n3); prt("101"); IntSet even = newEmptySet(); intersection(even); prt("empty"); for (int i=1; i<=50; i=i+2) insert(i); prt("odd"); for (int i=0; i<=50; i=i+2) even.insert(i); even.prt("even"); union(even); prt("all"); } }