CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 14 of 14
  1. #1
    Join Date
    Dec 2008
    Posts
    10

    Question Stuck with A Trie implementation

    Hi guys,

    Anyone can give me some help for this Trie application. I implemented an insert method and a find method in the Trie class, and in the Scrab application, I inserted 3 strings into the Trie, and then use find method to check whether the string is in the Trie. The insert method seems working fine, but the find method cannot find the string. Please give me some help guys, I haven't touched any C/C++ things for a long time(working on Java), but now I need to reactivate my C/C++ skills. So please help me with that, Guys.

    The Trie class and Scrab applciation is as following:
    Code:
    #include "Trie.h"
    
    Trie::Trie() {
        valid = false;
    }
    
    //inserts a word into the trie,give the entry of the first char and last one
    bool Trie::insert(string::const_iterator first, string::const_iterator last) {
        Trie currentNode;
        if(first != last) {
            map<char,Trie>::iterator iter = children.find(*first);
            if(iter != children.end()) {
               currentNode = (iter->second);
               return (currentNode.insert(++first, last));
            }
            else {
               if((first == (last - 1)) && !valid) {
                   children.insert(map<char,Trie>::value_type(*first,currentNode));
                   cout << "last char of each word:" << *first << endl;
                   cout << "insert:childrensize after last char:" << children.size() << endl;
                   valid = true;
                   return 1;
               }
               else {
                   children.insert(map<char,Trie>::value_type(*first,currentNode));
                   cout << "insert:childrensize after every insert:" << children.size() << endl;
                   return currentNode.insert(++first,last);
               }
            }
        }
        return 1;
    }
    
    //checks if a word is in the trie, give the entry of the first char and last one
    bool Trie::find(string::const_iterator first, string::const_iterator last) const {
        if (first != last) {
            //Checks whether it reaches the end of the
            if(children.size() == 0 && valid){
                return 1;
            }
            if (children.find(*first) != children.end()) {
                Trie* currentNode = (children.find(*first))->second;
                //cout << "find:child:" << *(first);
                //cout << "find:children size:" << currentNode.children.size() << endl;
                return currentNode.find(first+1,last);
            }
            else {
                cout << "Something wrong~~" << endl;
                return 0;
            }
        }
        return 1;
    }
    
    class Scrab {
    
    public:
        Trie root;
        Scrab();
        ~Scrab();
    };
    
    Scrab::Scrab(){
        cout << "Initializing Scrab" << endl;
    }
    
    Scrab::~Scrab(){
        cout << "Destructing Scrab" << endl;
    }
    
    int main( int argc, const char* argv[] )
    {
        int total_words = 0;
        char* charSequence;
        Scrab scrab;
        cout << "***********************" << endl;
        cout << "* Scrabbinator Helper *" << endl;
        cout << "***********************" << endl;
        if (argc != 2) {
            cerr << "Please type in file path and name."<<endl;
        }
        if (argv[1] != NULL) {
            cout<<argv[1]<<endl;
            ifstream in;
            in.open(argv[1]);
            if(!in) { // file couldn't be opened
                cerr << "Error: file could not be opened" << endl;
                exit(1);
            }
            while(!in.eof()){
                //cout << "children size:" << scrab.root.children.size() << endl;
                //cout << "found or not:" << scrab.root.find(word.begin(),word.end()) <<  endl;
                string word;
                in>>word;
                if(word.length() != 0) {
                      if(scrab.root.insert(word.begin(),word.end()))
                          total_words++;
                      cout<<"result:"<<scrab.root.find(word.begin(),word.end())<<endl;
    
                }
            }
           cout<<"*******************************" <<endl;
            cout<<"Read " <<total_words<<" distinct word(s) from the file \'"<<argv[1]<<"\'"<<endl;
            cout<<"Please enter letter sequence and optional match pattern:"<<endl;
            cin >> charSequence;
            in.close();
        }
    Last edited by RICO_BEE; December 8th, 2008 at 11:13 PM.

  2. #2
    Join Date
    Dec 2008
    Posts
    10

    Re: Stuck with A Trie implementation

    Trie.h

    Code:
    #ifndef TRIE_H
    #define TRIE_H
    
    #include <iostream>
    #include <string>
    #include <set>
    #include <vector>
    #include <map>
    #include <utility>
    
    using std::cout;
    using std::endl;
    using std::vector;
    using std::string;
    using std::map;
    using std::set;
    using std::pair;
    using std::make_pair;
    
    // this new interface removes the valid vector `optimisation'
    // and uses a better C++ approach, with iterators and const members
    // our implementation does not use [] for vector and map
    
    // simple trie data structure
    class Trie {
    
      // private data members
      bool valid;
      //map<char, Trie> children;
    
    public:
      map<char, Trie> children;
      // constructor
      Trie();
    
      // inserts a word into the trie
      bool insert(string::const_iterator first, string::const_iterator last);
      // checks if a word is in the trie
      bool find(string::const_iterator first, string::const_iterator last) const;
      // searches for words in the trie matching letter sequence in fragments
      // stores words found in matches
      void search(set<string> &matches, vector<char> sequence, string prefix = "") const;
      // prints all words in the trie
      void print(string prefix = "") const;
      void printDebug();
      // destructor
      ~Trie();
    };
    Last edited by RICO_BEE; December 8th, 2008 at 09:19 PM.

  3. #3
    Join Date
    Nov 2008
    Location
    England
    Posts
    748

    Re: Stuck with A Trie implementation

    please edit your post and repost your code within code tags.
    Get Microsoft Visual C++ Express here or CodeBlocks here.
    Get STLFilt here to radically improve error messages when using the STL.
    Get these two can't live without C++ libraries, BOOST here and Loki here.
    Check your code with the Comeau Compiler and FlexeLint for standards compliance and some subtle errors.
    Always use [code] code tags [/code] to make code legible and preserve indentation.
    Do not ask for help writing destructive software such as viruses, gamehacks, keyloggers and the suchlike.

  4. #4
    Join Date
    Dec 2008
    Posts
    10

    Re: Stuck with A Trie implementation

    sorry about the mess, it has been edited already.

  5. #5
    Join Date
    Mar 2002
    Location
    St. Petersburg, Florida, USA
    Posts
    12,125

    Re: Stuck with A Trie implementation

    Quote Originally Posted by RICO_BEE View Post
    sorry about the mess, it has been edited already.
    What happens when you step through it with the debugger? Which line gives the first "unexpected" result?
    TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
    2008, 2009,2010
    In theory, there is no difference between theory and practice; in practice there is.

    * Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions
    * How NOT to post a question here
    * Of course you read this carefully before you posted
    * Need homework help? Read this first

  6. #6
    Join Date
    Dec 2008
    Posts
    10

    Question Re: Stuck with A Trie implementation

    Quote Originally Posted by TheCPUWizard View Post
    What happens when you step through it with the debugger? Which line gives the first "unexpected" result?
    Actually it doesnt have any exceptions, but it only can get to the first level of the trie. For example, if I tried to find the word "American" in the trie, it can find the first letter 'A', but then the size of the children map of 'A' will be 0. But I cannot find why it is 0, coz I already inserted the elements in the children map when inserted the strings.

    So really no idea about whats going on.

  7. #7
    Join Date
    Dec 2008
    Posts
    10

    Re: Stuck with A Trie implementation

    I suspect it could be something wrong the Trie object in the children map.

  8. #8
    Join Date
    Mar 2002
    Location
    St. Petersburg, Florida, USA
    Posts
    12,125

    Re: Stuck with A Trie implementation

    Quote Originally Posted by RICO_BEE View Post
    Actually it doesnt have any exceptions, but it only can get to the first level of the trie. For example, if I tried to find the word "American" in the trie, it can find the first letter 'A', but then the size of the children map of 'A' will be 0. But I cannot find why it is 0, coz I already inserted the elements in the children map when inserted the strings.

    So really no idea about whats going on.
    Exceptions have NOTHING to do with steeping through it with the debugger.

    As EACH individual line executes WRITE down the values of each variable that is used on that line.
    TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
    2008, 2009,2010
    In theory, there is no difference between theory and practice; in practice there is.

    * Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions
    * How NOT to post a question here
    * Of course you read this carefully before you posted
    * Need homework help? Read this first

  9. #9
    Join Date
    Dec 2008
    Posts
    10

    Question Re: Stuck with A Trie implementation

    Quote Originally Posted by TheCPUWizard View Post
    Exceptions have NOTHING to do with steeping through it with the debugger.

    As EACH individual line executes WRITE down the values of each variable that is used on that line.
    Yep, I know what you mean. I used GDB to debug it in Linux, the problem is the 2nd level nodes don't have any child when I try to use "find" method.

    For example, I inserted 4 words into the Trie, "Bob" , "Dog", "Sun", "Think" without problems. when I try to use "find" to search for "Bob", I can find 'B' without problems, and when I step into children map of 'B', it says size of children is 0. I set breakpoints in the find the value of the children.size,,, it is always 0.

    I suspected that in my recursive method,, I didn't process the children properly. 'children ' is a map<char,Trie> member of Trie class.

  10. #10
    Join Date
    Nov 2011
    Posts
    2

    Red face Re: Stuck with A Trie implementation

    Hi... am planning to implement a dictionary using trie.. so i need help.. ve u implemented it in JAVA or C if so help me wit d code or tell me how to proceed

  11. #11
    Join Date
    Nov 2011
    Posts
    2

    Re: Stuck with A Trie implementation

    Hi... am planning to implement a dictionary using trie for my mini project.. so i need help.. ve u implemented it in JAVA or C if so help me wit d code or tell me how to proceed

  12. #12
    Join Date
    Oct 2006
    Location
    Sweden
    Posts
    3,654

    Re: Stuck with A Trie implementation

    First of all you need to replace your keyboard since several keys are broken...
    See this http://www.codeguru.com/forum/announcement.php?f=7 under section Your Posting
    Debugging is twice as hard as writing the code in the first place.
    Therefore, if you write the code as cleverly as possible, you are, by
    definition, not smart enough to debug it.
    - Brian W. Kernighan

    To enhance your chance's of getting an answer be sure to read
    http://www.codeguru.com/forum/announ...nouncementid=6
    and http://www.codeguru.com/forum/showthread.php?t=366302 before posting

    Refresh your memory on formatting tags here
    http://www.codeguru.com/forum/misc.php?do=bbcode

    Get your free MS compiler here
    https://visualstudio.microsoft.com/vs

  13. #13
    Join Date
    Oct 2006
    Posts
    2

    Re: Stuck with A Trie implementation


  14. #14
    Join Date
    Jun 2012
    Posts
    2

    Re: Stuck with A Trie implementation

    children map when inserted the strings.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured