美文网首页
Concerning Graph Part VI Symbol

Concerning Graph Part VI Symbol

作者: 刘煌旭 | 来源:发表于2021-01-14 00:32 被阅读0次

We address symbol graph in this post.
We use RBBSTree as the underlying symbol table here, but a hash table might be more efficient.

#include "graph.c"
#include "red_black_bst.c"
#ifndef SYMBOL_GRAPH
#define SYMBOL_GRAPH
typedef struct SymbolGraphStruct {
    RBBSTree st;
    char **keys;
    Graph g;
}*SymbolGraph;

SymbolGraph SymbolGraphCreate(char *fileName, char *delim) {
    SymbolGraph sg = (SymbolGraph)malloc(sizeof(*sg));
    sg->st = RBBSTreeCreate(RBBSTKeyTypeString);

    FILE *fp = fopen(fileName, "r");
    char line[100];
    while (fgets(line, 100, fp) != NULL) {
        int linel = strlen(line);
        if (line[linel - 1] == '\n') { line[linel - 1] = '\0'; }
        char *sub = strtok(line, delim);
        while (sub != NULL) { 
            if (RBBSTreeGet(sg->st, sub) == INT_MIN) { RBBSTreeSet(sg->st, sub, RBBSTreeCount(sg->st)); } 
            sub = strtok(NULL, delim);
        }
    }

    sg->g = GraphCreateV(RBBSTreeCount(sg->st));
    sg->keys = (char**)malloc(sizeof(char*) * RBBSTreeCount(sg->st));
    rewind(fp);
    while (fgets(line, 100, fp) != NULL) {
        int linel = strlen(line);
        if (line[linel - 1] == '\n') { line[linel - 1] = '\0'; }
        char *sub = strtok(line, delim);
        int v = RBBSTreeGet(sg->st, sub);
        if (sg->keys[v] == NULL) { sg->keys[v] = String(sub); }
        sub = strtok(NULL, delim);
        while (sub != NULL) {
            int w = RBBSTreeGet(sg->st, sub);
            if (sg->keys[w] == NULL) { sg->keys[w] = String(sub); }
            GraphAddEdge(sg->g, v, w);
            sub = strtok(NULL, delim);
        }
    }
    fclose(fp);

    return sg;
}

bool SymbolGraphContains(SymbolGraph sg, char *s) { return RBBSTreeGet(sg->st, s) != INT_MIN; }

int SymbolGraphIndex(SymbolGraph sg, char *s) { return RBBSTreeGet(sg->st, s); }

char* SymbolGraphName(SymbolGraph sg, int v) { return v < sg->g->v ? sg->keys[v] : NULL; }

Graph SymbolGraphGraph(SymbolGraph sg) { return sg->g; }
#endif

相关文章

网友评论

      本文标题:Concerning Graph Part VI Symbol

      本文链接:https://www.haomeiwen.com/subject/vuucaktx.html