/* *********************************************************
 *
 * Anagrams
 *
 * Topics: Map, Lexicon, compound collections
 *
 * Cynthia Lee (c) 2014, based on concept by Keith Schwarz
 *
 * This tool processes every English word, and creates a
 * database of anagrams. It then supports a query interface,
 * allowing the user to enter a word and get a list of
 * words that are anagrams of that word.
 *
 * **********************************************************/
#include "console.h"
#include "map.h"
#include "lexicon.h"
#include "vector.h"
#include "string.h"
#include "simpio.h"

using namespace std;

#include <iostream>
#include <algorithm> //for sort()


string sortWord(string word);


int main() {
    // Make and populate lexicon of english words
    Lexicon english("dictionary.txt");

    // Make and populate anagram map
    Map<string, Vector<string>> anagrams;
    for (string word : english) {
        anagrams[sortWord(word)]+= word;
    }

    // Let user enter words, and print the word's anagrams
    string query = getLine("Enter a word to find anagrams (or \"q\" to quit): ");
    while (query != "q"){
        string sorted = sortWord(query);
        if (anagrams.containsKey(sorted)){
            cout << "Your anagrams (including the word itself) are:" << endl;
            Vector<string> matches = anagrams[sortWord(query)];
            for (string anagram : matches){
                cout << anagram << endl;
            }
            cout << endl;
        } else {
            cout << "\"" << query << "\" has no anagrams. Please try again." << endl;
        }
        query = getLine("Enter a word to find anagrams (or \"q\" to quit): ");
    }
    return 0;
}

/*
 * sortWord()
 *
 * Takes the given word, sorts the characters in alphabetical order,
 * and returns the resulting string.
 */
string sortWord(string word){
    sort(word.begin(), word.end());
    return word;
}

