Click here to Skip to main content
15,902,875 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
hello my friends
i have a problem about implementation Trie with C++
the project which is included,must have the following
1. Ability to create a hollow tree
2. Ability to insert a new string tree
3. Ability to search for a specific string in a tree
4. The ability to find all the strings that begin with a particular substring
5. Find the following string that contains a specific string.
6. The ability to find all strings that end in a particular substring.
7. List all fields in the tree
8. View tree
9. Exit the program
now when I run 2 options, with a word that contains the string, number printing letters and numbers that come from unknown
next question : What options using option 4, 5 and 6 do. Please indicate in practice
and how can i view tree??
please Help me,I need this code.tanks

C#
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include<malloc.h>
#define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0])

// Alphabet size (# of symbols)
#define ALPHABET_SIZE (26)
// Converts key current character into index//tabdile kelide charachtere jari be index
// use only 'a' through 'z' and lower case // faghat az a ta z va horofe kochak estefade mikonad
#define CHAR_TO_INDEX(c) ((int)c - (int)'a')
static int test;
// trie node
typedef struct trie_node trie_node_t;
struct trie_node
{
    int value;
    trie_node_t *children[ALPHABET_SIZE];
};

// trie ADT
typedef struct trie trie_t;
struct trie
{
    trie_node_t *root;
    int count;
};

// Returns new trie node (initialized to NULLs)//gereye derakhte jadid ra bar migardanad ( meghdar dehie avalie ba Null)
trie_node_t *getNode(void)
{
    trie_node_t *pNode = NULL;

    pNode = (trie_node_t *)malloc(sizeof(trie_node_t));//meghdare hafeze dar tire_node_t ra bar hasbe byte ba estefade az malloc be barname takhsis midahad,va noe in eshare gar az node node_trie_t mibashad//1 Argoman (meghdar fazaye morede niaz) ra bar migardanad ((meghdar fazaye moshakhasi ra be barname bar migardanad))
    //size of => tole motaghayer va ya noe motaghayer ra bar hasbe byte mitavan be dast avard.
    if(!pNode)//hich hafezei be pnode takhsis dade nashode
    {
        printf("\n\n takhsise faza anjam nashod !! ");
        return NULL;
    }
    if( pNode )
    {
        int i;
        pNode->value = 0;

        for(i = 0; i < ALPHABET_SIZE; i++)
        {
            pNode->children[i] = NULL;
        }
    }

    return pNode;
}

// Initializes trie (root is dummy node)
void initialize(trie_t *pTrie) // methode meghdar dehie avalie az noe void ba 1 meghdar az noe eshare gar be name pTrie.
{
    pTrie->root = getNode();
    pTrie->count = 0;
}

// If not present, inserts key into trie
// If the key is prefix of trie node, just marks leaf node
void insert(trie_t *pTrie, char key[])
{
    int level;
    int length = strlen(key);//key= arayei az charechter ha, tole key ra dar lengh mirizim
    int index;
    trie_node_t *pCrawl;

    pTrie->count++;
    pCrawl = pTrie->root;

    for( level = 0; level < length; level++ )
    {
        index = CHAR_TO_INDEX(key[level]);
        if( !pCrawl->children[index] )
        {
            pCrawl->children[index] = getNode();
        }

        pCrawl = pCrawl->children[index];
    }

    // mark last node as leaf//alamat gozarie akharie gereh be onvane barg
    pCrawl->value = pTrie->count;
}

// Returns non zero, if key presents in trie
int search(trie_t *pTrie, char key[])
{
    int level,i;
    int length = strlen(key);
    int index;
    trie_node_t *pCrawl;

    pCrawl = pTrie->root;

    for( level = 0; level < length; level++ )
    {
        index = CHAR_TO_INDEX(key[level]);

        if( !pCrawl->children[index] )
        {
            return 0;
        }

        pCrawl = pCrawl->children[index];
    }

    return (0 != pCrawl && pCrawl->value);
}
//after having the prefix traverse the sub tree of trie to fetch and print the suggestions
void traverse(trie_node_t *pCrawl, char key[],int index)
{
   int i;
   char *temp;

   if(!pCrawl)
   {

       return ;
   }
   if(pCrawl->value!=0&&pCrawl!=NULL)
   {
       printf("%s\n",key);

}
   for(i=0;i<26;i++)
   {

       temp=(char *)malloc(sizeof(char)*strlen(key)+2);
       strcpy(temp,key);
       temp[strlen(key)]=(char)(97+i);
       temp[strlen(key)+1]='&#92&#48';
       if(pCrawl->children[i]!=NULL)
       traverse(pCrawl->children[i], temp,i);


       free(temp);
}


}
//travel down the trie upto the prefix and then look for suggestion using traverse function
// harkat in derakht ta pishvand va sepas peyda kardane pishnehad ba estefade az tabe'e traverse
int suggestions(trie_t *pTrie, char key[]) //
{
    int level,i;
    int length = strlen(key);
    int index;
    trie_node_t *pCrawl;

    pCrawl = pTrie->root;
    if(strcmp(key,"")==0)
    {
        printf("The input is NULL!!");
        return 0;
    }

    for( level = 0; level < length; level++ )
    {
        index = CHAR_TO_INDEX(key[level]);

        if( !pCrawl->children[index] )
        {

        printf("Prefix is not present");
            return 0;
        }

        pCrawl = pCrawl->children[index];
    }
traverse(pCrawl, key,index);
}
//checks whether the string contains lowercase only
/*int check(char key[])
{
int i,status;
i=0;
status=-1;
while(key[i]!='&#92&#48')
    {
        if(!(key[i]<='z'&&key[i]>='a'))
        {   status=0;
            return status;
        }
        i++;
    }
status =1;
return 1;
}*/


// Driver
int main()
{

    int i,status,prompt;
    char inputString[30];
    prompt=1;
    trie_t trie;
    initialize(&trie);
while(prompt!='4')
{
    printf("\nPress 1 to insert a string into the database\nPress 2 to look for suggestions\nPress 3 to search a string\nPress 4 to exit\n");
    scanf("%d",&prompt);
    switch(prompt)
    {
        case 1 : printf("\nPlease enter the string\n");
                   scanf("%s",inputString);
           if(strcmp(inputString,"")==0)
            {
                printf("Empty strings are not allowed");
                break;
            }
    /*   if(check(inputString)==0)
            {
                printf("\nSorry Only lower case alphabets are allowed !!\n");
                break;
            }*/
                   insert(&trie, inputString);
                   strcpy(inputString,"");
                   break;
        case 2 : printf("\nPlease enter the pattern\n");
                   scanf("%s",inputString);
           if(strcmp(inputString,"")==0)
            {
                printf("Empty strings are not allowed");
                break;
            }
         /*  if(check(inputString)==0)
            {
                printf("\nSorry Only lower case alphabets are allowed !!\n");
                break;
            }*/
           printf("\nThe patterns are ::\n");
                   suggestions(&trie,inputString);
                 //  strcpy(inputString,"");
                   break;
        case 3 : printf("\nPlease enter the string to be searched\n");
                   scanf("%s",inputString);
           if(strcmp(inputString,"")==0)
            {
                printf("Empty strings are not allowed");
                break;
            }
    /*     if(check(inputString)==0)
            {
                printf("\nSorry Only lower case alphabets are allowed !!\n");
                break;
            }*/
                   status=search(&trie,inputString);
                   strcpy(inputString,"");
            if(status==0)
                printf("\nThe string you are looking is not present in the databse\n");
            else
                printf("The string is present in the database");

                   break;

    case 4 : return 0;
        default: printf("Invalid option!!Please try again!!!!\n\n");
                 break;
    }

}

    return 0;
}
Posted
Updated 9-Jan-15 12:29pm
v2
Comments
[no name] 9-Jan-15 15:53pm    
And where your code make problems?
Member 10321132 9-Jan-15 15:57pm    
I do not know I want to know where is the problem code, when I run 4 switch between characters and odd numbers are printed
My compiler is Dev c++
[no name] 9-Jan-15 16:00pm    
Mr. "Software Developer (Senior), Student": And you wrote the code by yourself?
Member 10321132 9-Jan-15 16:03pm    
No, I've just changed some places, if you can please help me, because I am the project must be delivered tomorrow.

This is not a very well posed question. First of all, you need to explain how is the code you show related to your question? What did you try to achieve, how, what did you try, what did you expect and what did you get instead, why do you feel it's wrong. Also, we cannot discuss "view tree" topic without knowing what is your platform, what UI or graphics library you are using, what's required for the view, etc.

The quick look at your code suggests that you should better start over. First of all, you should not put and I/O in the classes like tree, no printf, nothing like that. You need to create a distinct Tree and TreeNode classes (note that your tag says you are writing in C++, not!), and all the methods should be either class instance or static methods, and those classes should be totally abstracted from I/O. For example, you can have a method for adding a node, but the input of the note string data should be done in some test/demo/debug class or function.

Using those "case 1", "case 2", "case 4" is unacceptable. They don't tell anything to the one reading your code. At least, use some enumeration type. Anyway, it should not be in your tree-related classes. Also, avoid all those immediate constants, except most fundamental ones, like 0, 1, null, etc. All those 26, '\0', 97, hard-coded strings — are very bad, kills all the maintainability of your code. At least declare the explicit const objects. Don't show all that commented-out code, respect the reader just a bit…

—SA
 
Share this answer
 
Telling from your questions, the code you are showing us here is not yours, but somebody else's and you are just looking for something to turn in as your homework.

But that is not like things work here. We would not do you a favor by just giving you a piece of code. If you can do your homework, but just have a particular problem with one of the points, then you can post here and most likely get help understanding the subject you need. If, however, you have no clue at all how to solve your homework, I think you are wasting your time in that course, at least at this moment. Start all over again and try to get an understanding of the basics. From there, work on to more complex things. In program there is no way of understanding things just "a little". Either you understand it or not - and if not, you will never succeed in being a software developer.

Sorry, but at this stage nobody can help you, except yourself.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900