import time
import random 
from largest_bucket import largest_bucket
from mean_bucket import mean_bucket
############################################################
def h0(key, ht_size):
    return 0

def h1(key, ht_size):
    return ord(key[0]) % ht_size

def h2(key, ht_size):
    x = 0
    for i in range(len(key)):
        ascii_code = ord(key[i])
        x = x + ascii_code
    return x % ht_size
    
def h3(key,ht_size):
    x = 0
    for i in range(len(key)):
        ascii_code = ord(key[i])
        x = 128 * x + ascii_code
    return x % ht_size
############################################################
def new_hash_table(size):
    ht = []
    for i in range(0,size):
        ht.append([])
    return ht
    
def ht_insert(ht, key, hash_fun):
    if hash_fun == "h0":
        bucket = ht[h0(key,len(ht))] 
    elif hash_fun == "h1":
        bucket = ht[h1(key,len(ht))] 
    elif hash_fun == "h2":
        bucket = ht[h2(key,len(ht))] 
    elif hash_fun == "h3":
        bucket = ht[h3(key,len(ht))] 
    bucket.append(key)

def ht_search(ht, key, hash_fun):
    if hash_fun == "h0":
        bucket = ht[h0(key,len(ht))] 
    elif hash_fun == "h1":
        bucket = ht[h1(key,len(ht))] 
    elif hash_fun == "h2":
        bucket = ht[h2(key,len(ht))] 
    elif hash_fun == "h3":
        bucket = ht[h3(key,len(ht))] 
    for i in range(len(bucket)):
        if bucket[i] == key:
            return True
    return False

def run(hash_fun):
    hash_fun = str(hash_fun)
    #create a hash table with 10000 buckets
    size = 100000
    start_time = time.time()
    ht = new_hash_table(size)
    end_time = time.time()
    
    print("Created hash table with ", size, " buckets in ", (end_time-start_time), " seconds")
    words_Array = []
    for i in range(size):
        word = ""
        randomWordLength= random.randint(4,10)
        for j in range(randomWordLength):
            word = word + chr(random.randint(97,122))
        words_Array.append(word)

    
    assert(size == len(words_Array))
    
    # insert each word into the hash table
    insert_start = time.time()
    for words in words_Array:
        ht_insert(ht,words,hash_fun)
    insert_end = time.time()
       
    print ("Inserted ", len(words_Array), " words in ", insert_end - insert_start, " seconds.")
        
    # lookup a hundred words
    lookup_start = time.time()
    for i in range(1000):
        random_word = words_Array[random.randint(0,len(words_Array)-1)]
        ht_search(ht,random_word,hash_fun)
    lookup_end = time.time()
    
    print ("Searched for 1000 words in",(lookup_end-lookup_start), "seconds","\n")
    
    print ("---Statistics for",hash_fun, "---","\n")
    print ("Number of entries in largest bucket:", largest_bucket(ht))
    print ("Mean size of non-empty buckets:", mean_bucket(ht))
    

