// CSE 373, Winter 2013, Marty Stepp // A HashIntSet object represents a set of integers using a hash table // as the internal data structure. // The hash table uses linear probing to resolve collisions. import java.util.Arrays; public class HashIntSet implements IntSet { private static final int EMPTY = 0; private static final int REMOVED = -9999999; // special value used on removal private static final double MAX_LOAD = 0.75; // load factor on which to rehash private int[] elements; private int size; // Constructs a new empty set of integers. public HashIntSet() { elements = new int[10]; size = 0; } // Adds the given value to this set, // if it was not already contained in the set. public void add(int value) { // resize if necessary if (loadFactor() > MAX_LOAD) { rehash(); } // linear probing to find proper index int h = hash(value); while (elements[h] != EMPTY && elements[h] != value && elements[h] != REMOVED) { h = (h + 1) % elements.length; } // add the element if (elements[h] != value) { elements[h] = value; size++; } } // Returns whether the given value is found in this set. public boolean contains(int value) { // linear probing to find proper index int h = hash(value); while (elements[h] != EMPTY && elements[h] != value) { h = (h + 1) % elements.length; } return elements[h] == value; } // Returns true if there are no elements in this set. public boolean isEmpty() { return size == 0; } // Returns the hash table's "load factor", its ratio of size to capacity. public double loadFactor() { return (double) size / elements.length; } // Removes the given element value from this set, // if it was found in the set. public void remove(int value) { // linear probing to find proper index int h = hash(value); while (elements[h] != EMPTY && elements[h] != value) { h = (h + 1) % elements.length; } // remove the element if (elements[h] == value) { elements[h] = REMOVED; size--; } } // Returns the number of elements in this set. public int size() { return size; } // Returns a text representation of this set. // TODO: finish (this is not a proper toString; it shows the internal array) public String toString() { return Arrays.toString(elements); } // Debugging helper that prints the inner hash table. public void debug() { System.out.printf("%7s", "index"); for (int i = 0; i < elements.length; i++) { System.out.printf("%7d", i); } System.out.println(); System.out.printf("%7s", "value"); for (int i = 0; i < elements.length; i++) { System.out.printf("%7d", elements[i]); } System.out.println(); System.out.printf("%7s%7d\n\n", "size", size); } // hash function for mapping values to indexes private int hash(int value) { return Math.abs(value) % elements.length; } // Resizes the hash table to twice its original capacity. private void rehash() { int[] newElements = new int[2 * elements.length]; int[] old = elements; elements = newElements; size = 0; for (int n : old) { if (n != 0 && n != REMOVED) { add(n); } } } }