"""This is a program to solve the Jumble in the newspaper or online.
   It first builds a hash table version HT of a Wordlist structure from 
   the words in the designated sourcefile. The hash function h is
   invariant under permutation.  

   Then, the program enters a loop in which it carries out the following steps:

   1. prompt the user for a scrambled word w;
   2. compute h(w);
   3. see if any word in HT( h(w) ) contains exactly the same letters as w;
   4. if so, print the solution and continue;
   5. if not, print a failure message and continue.

   For each step of the process, keep statistics on time and space
   usage.  

   """

######################################################################
#                                                                    #
#                             HashSolver                             #
#                                                                    #
######################################################################

import time
import Wordlist2

# File wordslist contains a list of ~114K English words, including
# some very bizarre words. 
inputFileName = "scrambledwordslist"

# inputFileName = "scrambledwords56"

def main():
    start = time.time()

    wordlist = Wordlist2.WordlistHash()
    print("Using hash table wordlist.")
    print("Creating wordlist")

    wordlist.addWordsFromFile( inputFileName, lambda x: len(x) in [5, 6] )
    print( "The Wordlist contains ", len( wordlist ), " words.")
    end = time.time()
    empties, lf = wordlist.loadFactor()
    print("There are", empties, "empty buckets")
    print("Non-empty buckets have an average length of", lf)
    print("Building the Wordlist took %2.3f seconds" % (end - start))
    
    # Some test code to print out distibution of bucket counts.
    # wordlist.bucketCounts()

    # Execute this loop until the user decides to exit. 
    while True:
        word = input ("\nEnter a scrambled word (or EXIT):  ")
        start = time.time()
        word = word.strip().lower()
        if not word.isalpha():
            print( "Word contains illegal characters. Try again" )
            continue
        if (word == "exit"):
            print( "Thanks for playing!  Goodbye." )
            break

        permFound, comparisons = wordlist.findPerm( word )
        if permFound:
            print ("Found word: " + permFound)
        else:
            print("Sorry.  I can't solve this jumble!  Try again.")
        end = time.time()

        # Print out the stats on this attempt.
        print("Solving this jumble took %2.5f seconds" % (end - start))
        print("Made ", comparisons, " comparisons.")
    
main()
