/* * IntSetMixed.java * */ package datastructures; /** * * @author hs */ public class IntSetMixed implements IntSet { private int MAX = 2000; private boolean [] smallPosElem; private boolean [] smallNegElem; private IntSet1 vRep = new IntSet1();; // int values -MAX < i < +MAX are represented by two boolean arrays // larger number by a vector representation of int sets // Using the constructor with an positive integer arguments changes MAX. // abstr (o) = {n | o.vRep.contains(n)} // union { j | 0 <= j < MAX & o.smallPosElem[j]} // union { -j| 1 <= j < MAX & o.smallNegElem[j]} // where o is an object of Type IntSetMixed // repInv: vRep != null && and for all n: vRep.contains(n) // => n <= -MAX | +MAX<=n // && smallNegElem[0] = false // && repInv(vectorRep) /** Creates a new instance of IntSetMixed */ public IntSetMixed() { smallPosElem = new boolean[MAX]; smallNegElem = new boolean[MAX]; } public IntSetMixed(int n) { //pre: n > 0; smallPosElem = new boolean[n]; smallNegElem = new boolean[n]; } public void add(int e) { // effects: .... just like the code.... if (e >= MAX || e <= -MAX) vRep.add(e); else if (e < MAX && 0 <= e) smallPosElem[e] = true; else smallNegElem[-e] = true; } public boolean contains(int e) { if (e >= MAX || e <= -MAX) return vRep.contains(e); else if (e < MAX && 0 <= e) return smallPosElem[e] ; else return smallNegElem[-e]; } public boolean isEmpty() { return vRep.isEmpty() && numberOfSmallElem()==0; } private int numberOfSmallElem() { int res = 0; if (smallPosElem[0]) res++; int i = 1; while ( i < MAX){ if (smallPosElem[i]) res++; if (smallNegElem[i]) res++; i++; } return res; } public boolean remove(int e) { if (e >= MAX || e <= -MAX) return vRep.remove(e); if (0 <= e && e < MAX ) { if (smallPosElem[e]) { smallPosElem[e]=false; return true;} } else if (smallNegElem[-e]) { smallNegElem[-e]=false; return true;} return false; } public int size() { return numberOfSmallElem() + vRep.size(); } public void showSet() { System.out.println(); for (int i=0; i < MAX; i++) if (smallPosElem[i]) System.out.print(i + ", "); for (int i=1; i < MAX; i++) if (smallNegElem[i]) System.out.print(-i + ", "); vRep.showSet(); } }