
/**
 * Title:
 * Description:  Starting point for Hash exercise, CSC 220
 * Copyright:    Copyright (c) 2002
 * Company:
 * @author       Burton Rosenberg
 * @version 1.0
 */

public class MyHashTable {

  private static final int DEFAULT_SIZE = 4 ;
  boolean debug ;
  boolean useSingleHashing ;

  private String [] ht ; // the hash table ;
  int htSize ;
  int collisions = 0 ;

  public MyHashTable() {
     this(DEFAULT_SIZE) ;
  }

  public MyHashTable(int logSize) {
     htSize = 1<<logSize ;
     ht = new String[htSize] ;
  }

  private int primaryHashFunction( int hashCode ) {
     int i = hashCode % htSize ;
     if ( i<0 ) i+= htSize ;
     return i ;
  }

  private int secondaryHashFunction( int hashCode ) {
     if ( useSingleHashing ) return 1 ;
     int i = hashCode % 7 ;
     if ( i<0 ) i+= 7 ;
     return 2*i+1 ;
  }

  public void insert(String s) {
     if ( debug )
         System.out.println("insert: adding "+s) ;
     int i = primaryHashFunction( s.hashCode() ) ;
     if ( ht[i] != null ) {
       if ( debug ) System.out.println("  collision with " + ht[i] ) ;
       collisions++ ;
     }
     ht[i] = s ;
  }

  public void printHashTable() {
     System.out.println("\nHash Table:");
     for ( int i=0; i<htSize; i++ ) {
       System.out.println(i+": "+ht[i]) ;
     }
     System.out.println() ;
  }

}
