Пример #1
0
static void generateAllPossibleWords(const Grid<char> & boggleBoard, Set<string> & wordsSpottedSoFar,
                                     const Lexicon & english, int rowIndex, int colIndex, string buildingWord,
                                     Set<coord> wordPath){
    buildingWord += boggleBoard[rowIndex][colIndex];
    if (buildingWord.size() >= kMinGuessLength && english.contains(buildingWord)
           && !wordsSpottedSoFar.contains(buildingWord)) {
         wordsSpottedSoFar.add(buildingWord);
         recordWordForPlayer(buildingWord, COMPUTER);
    }
    if (!english.containsPrefix(buildingWord)) return;
    for (int i = -1; i <= 1; i++) {
        for (int j = -1; j <=1; j++){
            if(isShiftValid(boggleBoard, rowIndex, colIndex, i, j)){
                coord nextPos;
                nextPos.row = rowIndex + i;
                nextPos.col = colIndex + j;
                if (!wordPath.contains(nextPos)){
                    wordPath.add(nextPos);
                    generateAllPossibleWords(boggleBoard, wordsSpottedSoFar, english,
                                             rowIndex + i, colIndex + j, buildingWord, wordPath);
                    wordPath.remove(nextPos);
                }
            }
        }
    }
}
Пример #2
0
//credit to erickwill, his code guided me to the answer
void recursiveFindWord(int row, int col,std::string soFar, Grid<char> &grid, Lexicon words, Vector<std::string> &foundWords)
{
    char orig = grid.get(row,col);
    soFar = soFar + grid.get(row,col);
    drawCubes(grid);
    cout << "row = " << row << " col = " << col << endl;
    cout << "sofar = " << soFar << endl;

    if(words.contains(soFar) && !containsWord(foundWords,soFar)){
        cout << "contains word: " << soFar << endl;
        foundWords.push_back(soFar);
        return;
    }
    if(!words.containsPrefix(soFar)){
        cout << "does not contain prefix: " << soFar << endl;
        return;
    }

    for(int i = -1; i < 2; i++){
        for(int j = -1; j < 2; j++){
            if(row+i>=0 && col+j >=0 && row+i < grid.numRows() && col+j < grid.numCols() && (row+i < grid.numRows() && col+j < grid.numCols())
               && !(i==0 && j==0) && grid.get(row+i,col+j) != '~')
               {
                grid.set(row,col,'~');
                recursiveFindWord(row+i,col+j,soFar,grid,words,foundWords);
                grid.set(row,col,orig);
               }
            }

    }
   return;
}
Пример #3
0
//! @brief read a text Bow file and fills a lexicon
//! @param fileIn the file to read
//! @param reader the file reader
//! @param lex the lexicon to fill
//! @param propertyAccessor
//! @param referenceProperties
void readBowFileText(ifstream& fileIn,
                     BoWBinaryReader& reader,
                     Lexicon& lex,
                     const PropertyAccessor& propertyAccessor,
                     set<LinguisticCode>& referenceProperties
                    )
{
    BoWText text;
    reader.readBoWText(fileIn,text);

    bool filterCategory = false;
    if ( referenceProperties.size() > 0 ) {
        filterCategory = true;
    }

    BoWTokenIterator it(text);
    while (! it.isAtEnd()) {
        const BoWToken& token = *(it.getElement());
        if (filterCategory) {
            set<LinguisticCode>::const_iterator referencePropertyIt =
                referenceProperties.find(propertyAccessor.readValue(token.getCategory()));
            if ( referencePropertyIt != referenceProperties.end() ) {
                lex.add(getStringDecomp(&token),token.getIndexString());
            }
        }
        else {
            lex.add(getStringDecomp(&token),token.getIndexString());
        }
        it++;
    }
}
Пример #4
0
/*
 * Recursive Computer Search
 *
 * Recursively searches the Boggle board to find all the
 * words that can be made on the board and haven't
 * been guessed correctly by the human player
 */
void recursiveComputer(int row, int col, string word, Grid<string>& board, Lexicon& dictionary, Set<string>& results, Grid<bool>& visitedCubes, int& computerScore, Set<string>& usedWords){
    if(!board.inBounds(row, col)) return;
    if(dictionary.contains(word) && word.length() >= 4) {
        if (!results.contains(word) && !usedWords.contains(word)) {
            computerScore += word.length() - 3;
            results.add(word);
        }
    }

    if(!dictionary.containsPrefix(word)){
        return;
    }
    word = word + board[row][col];

    visitedCubes[row][col] = true;

    for(int i = -1; i <= 1; i++){
        for(int j = -1; j <= 1; j++){
            if(visitedCubes.inBounds(row + i, col + j) && !visitedCubes[row + i][col + j]){
                recursiveComputer(row + i, col + j, word, board, dictionary, results, visitedCubes, computerScore, usedWords);
            }
            if(visitedCubes.inBounds(row + i, col + j) && dictionary.contains(word) && !results.contains(word) && word.length() >=4) {
                computerScore += word.length() - 3;
                results.add(word);
            }
        }
    }
    visitedCubes[row][col] = false;
}
Пример #5
0
string Levenshtein::getPath(Lexicon &lex)
{
	string path_ops = this->getPathOps();

	string path = "";
	unsigned int trans_counter = 0, ref_counter = 0;

	for (unsigned int i=0; i<path_ops.size(); i++)
	{
		switch (path_ops[i])
		{
			case 'm':
				path += "(m:"+lex.getWord(trans_v[trans_counter])+")";
				trans_counter++;
				ref_counter++;
				break;
			case 'i':
				path += "(i:"+lex.getWord(ref_v[ref_counter])+")";
				ref_counter++;
				break;
			case 'd':
				path += "(d:"+lex.getWord(trans_v[trans_counter])+")";
				trans_counter++;
				break;
		}
	}
	return path;
}
Пример #6
0
//return a string vector as the shortest ladder, if found
//return an empty vector, if not found
Vector<string> bfs(string &startingWord, string &endingWord) {
	Lexicon english("EnglishWords.dat");
	Lexicon wordUsed;
	Queue<Vector<string>> queue;
	Vector<string> ladder;

	ladder.push_back(startingWord);
	queue.enqueue(ladder);
	while (!queue.isEmpty()) {
		Vector<string> front = queue.dequeue();
		if (front.get(front.size() - 1) == endingWord)
			return front;
		string current = front.get(front.size() - 1);
		for (int i = 0; i < current.size(); i++)
			for (char j = 'a'; j <= 'z'; j++) 
				if (current[i] != j){
					string next = current;
					next[i] = j;
					if (!english.contains(next))
						continue;
					if (wordUsed.contains(next))
						continue;
					wordUsed.add(next);
					Vector<string> nextLadder = front;
					nextLadder.push_back(next);
					queue.enqueue(nextLadder);
				}
	}

	Vector<string> empty;
	return empty;
}
Пример #7
0
int main() {
    Lexicon english ("EnglishWords.dat");
    Lexicon usedWords; // need to check the unique word
    Queue<Vector<string>> result;
    string firstWord, secondWord;
    while(true){
        readWords (firstWord, secondWord, english);
        createFirstLadder(result, firstWord);
        usedWords.add(firstWord);
        while(!result.isEmpty ()){
            Vector<string> firstLadder = result.dequeue ();
            if(firstLadder.get (firstLadder.size () - 1) == secondWord){
                display(firstLadder);
                result.clear();
                usedWords.clear ();
                break;
            }
            string currentWord = firstLadder.get(firstLadder.size ()-1);
            usedWords.add(currentWord);
            createNextLadder(currentWord, firstLadder, usedWords, result, english);
        }
        /* If the ladder of the two entered words is impossible */
        if(!usedWords.isEmpty ()){
            cout << "Sorry, this ladder is impossible..." << endl;
        }
    }
    return 0;
}
Пример #8
0
bool InEnglish(const string &word)
{
  for(Lexicon::iterator it = english.begin(); it != english.end(); ++it)
    if(word == *it) return true;

  return false;
}
Пример #9
0
void CCmpLexicon::WriteToken(const char* inText, obit_stream& ioBits)
{
	Lexicon::iterator i = lower_bound(lexicon.begin() + 1, lexicon.end(), LexEntry(inText, 0));
	if (i != lexicon.end() && strcmp(inText, (*i).text) == 0)
	{
		Push(ioBits, (*i).code, (*i).cnt);
	}
	else
	{
		Push(ioBits, lexicon[0].code, lexicon[0].cnt);

		for (const char* p = inText; *p; ++p)
		{
			RestChar e;
			e.ch = static_cast<unsigned char>(*p);
			RestCharacters::iterator i = lower_bound(rest.begin(), rest.end(), e); 
			assert(i != rest.end());
			assert((*i).ch == static_cast<unsigned char>(*p));
			
			Push(ioBits, (*i).code, (*i).cnt);
		}
			
		Push(ioBits, rest[0].code, rest[0].cnt);
	}
}
Пример #10
0
/* ListCompletions(string, Lexicon):
 * Prints all words from the lexicon that can be formed by extending
 * the given digit sequence.
 */
void ListCompletions(string digits, Lexicon & lex) {
	int index=0;
	
	/*find the first digit*/
	while(index<(int)digits.length() && !isdigit(digits[index]))
		index++;

	/*Don't start checking until the digits have been entirely converted to letters*/
	if(index == digits.length() ){
		string word = digits; //redundant, but helps me understand
		/*Lexicon doesn't containPrefix=>these aren't the droids I'm looking for*/
		if(!lex.containsPrefix(word)) return;
		
		/*Otherwise check if the current word is in the lexicon and print it if it is*/
		if( lex.contains(word)){
			cout << "\t" << word << endl;
		}

		/*...and then try recursively checking after adding each letter*/
		for( char ch='a'; ch<='z'; ++ch){
			string newWord = digits + ch;
			ListCompletions(newWord, lex);
		}
		return;
	}

	/*make a prefix out of the current letters, check what could come next, and recursively check each*/
	string prefix = digits.substr(0, index);
	string digitLetters = letterSets[digits[index] - '0'];	//subtracting '0' converts digits[index] a char to an int
	int i=0;												//not intuitive at all
	while(i<digitLetters.length()){
		ListCompletions(prefix + digitLetters[i] + digits.substr(index + 1), lex );
		i++;
	}
}
AccountList AccountNumbersConverter::extractAccounts() {
    _accounts.clear();
    OCREntryListCIter iter;
    Lexicon lex;
    Account account;
    ChecksumCalculator checksumCalc;
    int expectedChecksum;

    for(iter = _entries.begin(); iter != _entries.end(); ++iter) {
        account.number = lex.parse( (*iter) );

        expectedChecksum = checksumCalc.checksumFor(account.number);

        account.checksum = ( (*iter).getChecksum() );
        account.isErroneous = (expectedChecksum != account.checksum);
        account.displayText = account.number;
        if (account.isErroneous) {
            account.displayText += " ERR";
        }

        _accounts.push_back(account);
    }

    return _accounts;
}
Пример #12
0
Vector<string> sloveBoggle(Grid<char> &grid, Point start, int depth, Vector<Point> &path, string &word, Lexicon &lex) {
	Vector<string> result; 
	if (depth > MAX_LENGTH) {
		// greater than maxium length, return
		// return lex.containsWord(word);
	} else {
		
		//recursion to the element around the current element.
		int i = start.x;
		int j = start.y;
		if(lex.containsWord(word) && depth >= MIN_LENGTH) {
			result.add(word);
		}
		for(Direction dir = TOPLEFT; dir <= LEFT; dir++) {
			if(isBound(grid, i, j, dir)) {
				Point new_start = adjustPoint(start, dir);
				if(isContainPoint(path, new_start)) continue;
				string new_word = word + grid.getAt(new_start.x, new_start.y);
				if(!lex.containsPrefix(new_word)) continue;

				path.add(new_start);
				depth++;
				Vector<string> res = sloveBoggle(grid, new_start, depth, path, new_word, lex);
				result = concateVec(result, res);
				path.removeAt(path.size() - 1);
				depth--;
			}
		}
	} 

	return result;
}
Пример #13
0
int ListWords(const map<char,string> &keypads,string prex,string digitSequence,string alber,Lexicon &lex){
    int count=0;
    if(digitSequence.empty()&&lex.containsPrefix(prex)){
        if(lex.containsWord(prex)){
            count++;
            cout<<prex<<endl;
        }
        for(unsigned int i=0;i<alber.size();i++){
            string p=prex;
            p.push_back(alber[i]);
            count+=ListWords(keypads,p,digitSequence,alber,lex);
        }
        return count;
    }
    if(!digitSequence.empty()&&lex.containsPrefix(prex)){

        string nextchar=(keypads.find(digitSequence[0]))->second;
        digitSequence.erase(digitSequence.begin());
        for(unsigned int i=0;i<nextchar.size();i++){
            string p=prex;
            p.push_back(nextchar[i]);
            count+=ListWords(keypads,p,digitSequence,alber,lex);
        }
    }
    return count;
}
string findWordLadder(string startWord, string endWord, Lexicon& wordsLexicon)
{
    Queue<Vector<string>> ladderQueue;
    Lexicon usedWords;

    Vector<string> startingLadder;
    startingLadder.add(startWord);

    ladderQueue.enqueue(startingLadder);
    usedWords.add(startWord);

    while(ladderQueue.size() > 0)
    {
        Vector<string> wordLadder = ladderQueue.dequeue();
        string lastWord = wordLadder[wordLadder.size() - 1];

        if(lastWord == endWord)
        {
            string returnValue = "Ladder found:";
            foreach(string word in wordLadder)
            {
                returnValue += " " + word;
            }

            return returnValue;
        }
// checks lexicon and prints all words that begin with the given prefix
void printValidWords(string prefix, Lexicon &lex){
    string alpha = "abcdefghijklmnopqrstuvwxyz";
    if(lex.containsWord(prefix)) cout << prefix << " ";

    if(lex.containsPrefix(prefix)){
        for(int i = 0; i < alpha.length(); i++){
            printValidWords(prefix + alpha.at(i), lex);
        } 
    }
}
Пример #16
0
int main()
{
	vector<unsigned int> trans = f.insertSentence("Dies ist ein Test");
	vector<unsigned int> ref = f.insertSentence("ein Test Dies ist");
	cout << trans[1] << trans[2] << trans[3] << endl;
	cout << f.getWord(trans[1]) << f.getWord(trans[2]) << f.getWord(trans[3]) << endl;
	//Bleu *current = new Bleu(trans,ref);

	return 0;
}
Пример #17
0
void checkLexicon(string indexLetters, Lexicon & lex) {
    string lowerCase = UpToLow(indexLetters);
    foreach (string word in lex) {
        Lexicon newLex;
        newLex.add(word);
        if(newLex.containsPrefix(indexLetters) || newLex.containsPrefix(lowerCase)) {
            cout << word << endl;
        }

    }
void ListCompletionsRec(Vector<string>prefixes, Lexicon & lex) {
    for (int i = 0; i < prefixes.size(); i ++) {
        string current = prefixes[i];
        if (lex.contains(current) || lex.containsPrefix(current)) {
            for (int i = 0; i < alphabet.length(); i ++) {
                current += alphabet[i];
                ListCompletionsRec(prefixes, lex);
            }
            
        }
    }
}
Пример #19
0
/**
 *  @brief Gets possible completions for a given word
 *  @param word The word to check for completions
 *  @param lex The lexicon to check completions against
 *  @param words A set that will be filled with possible completions
 *
 *  This function recursively checks for possible completions of a given
 *  word, using the provided lexicon.
 */
void getCompletions(string word, Lexicon &lex, Set<string> &words)
{
    if (lex.containsWord(word)) {
        words.add(word);
    }

    for (int i = 0; i < ALPHABET.size(); i++) {
        string newWord = word + ALPHABET[i];
        if (lex.containsPrefix(newWord)) {
            getCompletions(newWord, lex, words);
        }
    }
}
void streamInsertionLexiconTest() {
    Lexicon lex;
    cout << "empty lexicon: " << lex << endl;
    lex.add("alpher");
    cout << "1-item lexicon: " << lex << endl;
    lex.add("beter");
    lex.add("gammer");
    cout << "3-item lexicon: " << lex << endl;
    cout << "looping over lexicon..." << endl;
    for (string s : lex) {
        cout << s << endl;
    }
}
TIMED_TEST(LexiconTests, iteratorVersionTest_Lexicon, TEST_TIMEOUT_DEFAULT) {
    Lexicon lex {"ten", "twenty", "thirty", "forty"};
    try {
        for (std::string s : lex) {
            if (s.length() % 2 == 0) {
                lex.remove(s);
            }
        }
        assertFail("should not get to end of test; should throw exception before now");
    } catch (ErrorException ex) {
        assertPass("threw exception successfully");
    }
}
Пример #22
0
/* The function to solve the problem
 * Parameters:
 * start, dest => the two words to connect (MUST BE VALID WORDS)
 * dict        => Lexicon restores words
 * Return: The ladder / an empty Vector (when there is no solution)
 * No side effects
 */
Vector<string> find_ladder(const string & start, const string & dest, const Lexicon & dict)
{
    Vector<LadderStep> steps;  //keep answers
    Lexicon appeared;          //word that has appeared
    Queue<int> queue;          //the queue, saves the labels of steps

    //init
    steps.push_back(LadderStep(start,NO_MORE_STEP));
    appeared.add(start);
    queue.enqueue(0);
    int last = NO_MORE_STEP;   //the last step of the answer

    //main loop
    while(!queue.isEmpty()){
        int cur = queue.dequeue();

        if (steps[cur].str == dest) //arrives destination
        {
            last = cur;            //mark position
            break;
        }

        for (int i = 0; i < steps[cur].str.size(); ++i){
            for (char c = 'a'; c <= 'z'; ++c){           //generate all possible steps
                string next(steps[cur].str);
                next[i] = c;
                //A valid word that hasn't appeared yet?
                if (dict.contains(next)&& !appeared.contains(next)){
                    //enqueue
                    appeared.add(next);
                    steps.push_back(LadderStep(next, cur));
                    queue.enqueue(steps.size() - 1);
                }
            }
        }
    }

    Vector<string> tmp;       //the answer, reversed
    while(last != NO_MORE_STEP){       //has more steps?
        tmp.push_back(steps[last].str);
        last = steps[last].forward;    //go forward
    }

    //reverse to get the answer
    Vector<string> res;
    for (int i = tmp.size() - 1; i>=0; --i){
        res.push_back(tmp[i]);
    }

    return res;
}
TIMED_TEST(LexiconTests, hashCodeTest_Lexicon, TEST_TIMEOUT_DEFAULT) {
    Lexicon lex;
    lex.add("a");
    lex.add("bc");
    assertEqualsInt("hashcode of self lexicon", hashCode(lex), hashCode(lex));

    Lexicon copy = lex;
    assertEqualsInt("hashcode of copy lexicon", hashCode(lex), hashCode(copy));

    Lexicon lex2;   // empty

    // shouldn't add two copies of same lexicon
    HashSet<Lexicon> hashlex {lex, copy, lex2};
    assertEqualsInt("hashset of lexicon size", 2, hashlex.size());
}
Пример #24
0
/**
 * Function: oneHopAway
 * This helper function loops through each letter of the alphabet
 * at each position for a word passed through, checking whether
 * the newly formed word is both English and hasn't been used 
 * previously.  The latter check is maintained by a Lexicon
 * passed through by reference.
 * Parameters: dictionary cleared in main as constant reference, Lexicon of used words
 * passed by reference since it can be altered, constant reference to the word 
 * looking to build off of
 */
static Lexicon oneHopAway(const Lexicon& dictionary, Lexicon& usedWords, const string& topWord) {
	Lexicon oneHopAway;
	string alphabet = "abcdefghijklmnopqrstuvwxyz";
	for(int i = 0; i < topWord.length(); i++) {
		for(int j = 0; j < alphabet.length(); j++) {
			string testWord = topWord;
			testWord[i] = alphabet[j];
			if(dictionary.contains(testWord) && !usedWords.contains(testWord)) {
				oneHopAway.add(testWord);
				usedWords.add(testWord);
			}
		}
	}
	return oneHopAway;
}
Пример #25
0
/* Change the current word by one letter to create new true word.
 * Copy last ladder into new, and add new word to it.
 */
void createNextLadder(string &currentWord, Vector<string>& firstLadder, Lexicon& usedWords, Queue<Vector<string>>& result, Lexicon& english){
    for(int i = 0; i < currentWord.length (); i++){
        for(char c = 'a'; c <= 'z'; c++){
            if(currentWord[i] != c){
                string newWord = currentWord;
                newWord[i] = c;
                if(english.contains (newWord) && !usedWords.contains (newWord)){
                    Vector<string> nextLadder = firstLadder;
                    nextLadder.add(newWord);
                    result.enqueue (nextLadder);
                }
            }
        }
    }
}
Пример #26
0
bool isInLexicon(string word, Lexicon & lex) {
    if (lex.contains(word)) {
        return true;
    } else {
        return false;
    }
}
Пример #27
0
Lexicon findAllWords(Lexicon &dictionary, Grid<char> &charGrid, int gSize) {
	Lexicon result;
		for(int i = 0; i < gSize; i++) {  
			for(int j = 0; j < gSize; j++) {  
				string word; 
				word = charGrid[i][j];
				Lexicon computerWords;
				Lexicon temp;
				Grid<bool> boolGrid(gSize, gSize);
				wordSearch(dictionary, computerWords, charGrid, boolGrid, word, i, j);
				temp = computerWords;
				foreach(word in temp) {
					result.add(word);
				}
			}
		}
Пример #28
0
/*
 * Function: InputGuesses
 * -------------------------
 * Allows the user to input guesses. Runs checks on user guess to see if it meets all boggle requirements.
 */
void InputGuesses(Grid<char> boggleBoard, Lexicon wordList, Lexicon &usedWords, Grid<bool> usedDice)
{	
	cout << endl << "Ok, take all the time you want and find all the words you can!" << endl;
	cout << "Signal that you're finished by entering an empty line." << endl << endl;
	while (true) {
		int row= 0, col = 0;
		string userGuess = CheckUserGuess(wordList, usedWords); //checks if format rules are met
		if (userGuess == "") break; //checks if sentinel of user hitting return has been occured
		while (true) {
			if (FindUserGuessOnBoard(boggleBoard, row, col, "", userGuess, usedDice)) { 
                //checks if user guess can be created from boggleBoard
				usedWords.add(userGuess); //records user guess in lexicon of used words
				RecordWordForPlayer(userGuess, Human);
				UnhighlightBoard(boggleBoard);
				PlayNamedSound("excellent.wav");
				break;
			}
			if (!AdjacentPoint(boggleBoard.numRows(), boggleBoard.numCols(), row, col)) { 
                //checks if end of board has been reached without finding appropriate dice config
				cout << "You can't make that word! " << RandomizeResponse() << endl;
				PlayNamedSound("whoops.wav");
				break;
			}
		}
	}
}
static string getWord(Lexicon& english, string prompt) {
    while (true) {
        string response = trim(toLowerCase(getLine(prompt)));
        if (response.empty() || english.contains(response)) return response;
        cout << "Your response needs to be an English word, so please try again." << endl;
    }
}
Пример #30
0
void writeLexicon(ostream &out, Lexicon const &lexicon)
{
	for (Lexicon::const_iterator iter = lexicon.begin();
		iter != lexicon.end(); ++iter)
	{
		out << iter->first;

		for (map<string, size_t>::const_iterator tagIter = iter->second.begin();
			tagIter != iter->second.end(); ++tagIter)
		{
			out << " " << tagIter->first << " " << tagIter->second;
		}

		out << endl;
	}
}