开发者

Add items to a vector recursively

开发者 https://www.devze.com 2023-03-05 17:54 出处:网络
I\'m attempting to create a recursive function that outputs a vector of strings that contains all possible word combinations (while retaining order of letters) of a given string. Basically, the founda

I'm attempting to create a recursive function that outputs a vector of strings that contains all possible word combinations (while retaining order of letters) of a given string. Basically, the foundation of an auto-correct typing program, which produces effects similar that of the iPhone.

vector<string> allPossibleWords(string str, vector<vector<char> >开发者_JAVA技巧; & adjacentKeys)
{
  vector<string> words;

  cout << str << endl;

  if (str.length() == 0)
  {
    return words;
  }

  char firstLetter = str[0];
  string restOf = str.substr(1, str.length() - 1);
  int position = position_in_vector(firstLetter);

  for (int i = 0; i < adjacentKeys[position].size(); i++) 
  {
    string temp(1, adjacentKeys[position][i]);
    words.push_back(temp);
  }

  //allPossibleWords(restOf, adjacentKeys);
}

int position_in_vector(char letter)
{
  return (letter % 97);
}

For instance, if str is "yp", the output should be a vector containing the values {"yp", "tp", "gp", "hp", "up", "yo", "to", "go", "ho", "uo", "yl", "tl", "gl", "hl", "ul"}. If str is "y", the output should be a vector containing the values {"y", "t", "g", "h", "u"}.

The 26 vectors stored in adjacentKeys contain the letters adjacent to the letter that is stored in the first position of the vector.

a   qwsz
b   vghjn
c   xdfgv
d   zserfcx
//and so on

I am stuck with this function, and can't figure out how to recursively build this vector.


(Update: 2130 GMT Sunday: I've significantly changed my answer. I think this works now.)

Here is a complete program. There are other changes I think I would make, but I'm trying to keep to the spirit of your initial solution. It's important to return a single empty word when str.length()==0.

#include <vector>
#include <iostream>
using namespace std;


vector<string> allPossibleWords(string str, vector<vector<char> > & adjacentKeys)
{
        vector<string> words;

        // cout << "str=" << str << endl;

        if (str.length() == 0)
        {
                words.push_back("");
                return words;
        }

        char firstLetter = str[0];
        // cout << "firstLetter=" << firstLetter << endl;
        int positionInAdjacentKeys = 0;
        while(positionInAdjacentKeys < adjacentKeys.size() && adjacentKeys.at(positionInAdjacentKeys).front() != firstLetter) {
                ++ positionInAdjacentKeys;
        }
        vector<char> & adjacent = adjacentKeys.at(positionInAdjacentKeys);

        string restOf = str.substr(1, str.length() - 1);
        // cout << firstLetter << ":" << restOf << endl;

        // int position = position_in_vector(firstLetter);

        vector<string> recursiveWords = allPossibleWords(restOf, adjacentKeys);

        for (int i = 0; i < adjacent.size(); i++)
        {
                const string temp(1, adjacent[i]);
                // cout << "  temp=" << temp << endl;
                for(vector<string>::const_iterator i = recursiveWords.begin(); i != recursiveWords.end(); i++)
                {
                        // cout << "new word=" <<  temp + *i << endl;
                        words.push_back(temp + *i);
                }
        }
        return  words;
}


int main() {
        vector<vector<char> > adj;
        vector<char> v1;
        v1.clear();
        v1.push_back('p');
        v1.push_back('o');
        v1.push_back('l');
        adj.push_back(v1);
        v1.clear();
        v1.push_back('y');
        v1.push_back('t');
        v1.push_back('g');
        v1.push_back('h');
        v1.push_back('u');
        adj.push_back(v1);
        adj.push_back(v1);

        vector<string> words = allPossibleWords("yp", adj);

        for(vector<string> :: const_iterator i = words.begin(); i != words.end(); i++) {
                cout << *i << endl;
        }
}

return


Maybe something like this? I haven't tested it because I don't have your adjacentKeys matrix. It can probably be optimised a bit, but I don't think this approach will scale well at all.

I'd suggest attacking the problem from a different angle, perhaps storing your dictionary in some kind of K-ary tree, and having several pointers walking the tree, following branches based on your adjacency matrix. This would stop the generation of invalid words (and subsequent lookups to check validity) as branches would only exist where valid words exist.

using namespace std;

void allPossibleWordsHelper(const string& str, 
                            string::size_type index,
                            const vector<vector<char> >& adjacentKeys, 
                            vector<string>& results)
{
    if (str.length() == 0)
    {
        return;
    }

    std::string head = (index > 0) ? str.substr(0, index) : "";
    std::string tail = (index < str.length() - 1) ? str.substr(index + 1) : "";

    vector<string> possibleHeads;
    string::size_type headIndex = (str.length() - index) / 2;
    allPossibleWordsHelper(head, headIndex, adjacentKeys, possibleHeads);

    vector<string> possibleTails;
    allPossibleWordsHelper(tail, index + headIndex, adjacentKeys, possibleTails);

    int pos = str[index] - 'a';

    vector<string>::const_iterator headi;
    vector<string>::const_iterator headi_end = possibleHeads.end();

    vector<string>::const_iterator taili;
    vector<string>::const_iterator taili_end = possibleTails.end();

    vector<char>::const_iterator aki;
    vector<char>::const_iterator aki_end = adjacentKeys[pos].end();

    for(headi = possibleHeads.begin(); headi != headi_end; ++headi)
    {
        for (aki = adjacentKeys[pos].begin(); aki != aki_end; ++aki)
        {
            for (taili = possibleTails.begin(); taili != taili_end; ++taili)
            {
                string suggestedWord = *headi + *aki + *taili;

                results.push_back(suggestedWord);
            }
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消