Skip to content

Instantly share code, notes, and snippets.

@BenBrock
Created May 23, 2014 16:21
Show Gist options
  • Save BenBrock/d9c4cc535fa445ae505a to your computer and use it in GitHub Desktop.
Save BenBrock/d9c4cc535fa445ae505a to your computer and use it in GitHub Desktop.
Generate DOT Graph Description Language Based on a Tree Data Structure
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <dllist.h>
#define MAX_CHILDREN 32
typedef struct node {
int val;
char id;
struct node *parent;
struct node *children[MAX_CHILDREN];
} node;
typedef struct tree {
int size;
char gid;
struct node *root;
} tree;
node *new_node(tree *t, node *parent, int val);
tree *new_tree();
void gen_graph(tree *t, char *name);
int main(int argc, char **argv)
{
int i;
tree *t;
node *tmp;
t = new_tree();
srand48(time(0));
t->root->val = lrand48() % 10;
tmp = new_node(t, t->root, lrand48() % 10);
new_node(t, tmp, lrand48() % 10);
new_node(t, tmp, lrand48() % 10);
tmp = new_node(t, t->root, lrand48() % 10);
new_node(t, tmp, lrand48() % 10);
new_node(t, tmp, lrand48() % 10);
gen_graph(t, "muh_graph");
return 0;
}
node *new_node(tree *t, node *parent, int val)
{
int i;
node *n;
n = (node *) malloc(sizeof(node));
n->parent = parent;
n->val = val;
n->id = (t->gid)++;
for (i = 0; i < MAX_CHILDREN; i++) {
n->children[i] = NULL;
}
if (parent != NULL) {
for (i = 0; i < MAX_CHILDREN; i++) {
if (parent->children[i] == NULL) {
parent->children[i] = n;
break;
}
if (i == MAX_CHILDREN - 1) {
free(n);
return NULL;
}
}
}
(t->size)++;
return n;
}
tree *new_tree()
{
tree *t;
t = (tree *) malloc(sizeof(tree));
t->gid = 'a';
t->size += 1;
t->root = new_node(t, NULL, 0);
return t;
}
void gen_graph(tree *t, char *name)
{
int i;
Dllist q;
node *n;
printf("graph %s {\n", name);
q = new_dllist();
dll_append(q, new_jval_v(t->root));
while (!dll_empty(q)) {
n = jval_v(dll_first(q)->val);
dll_delete_node(dll_first(q));
printf("%c [label=\"%d\"];\n", n->id, n->val);
if (n->children[0] != NULL) {
/* Print route to children. */
for (i = 0; i < MAX_CHILDREN; i++) {
if (n->children[i] != NULL) {
printf("%c -- %c;\n", n->id, n->children[i]->id);
}
}
for (i = 0; i < MAX_CHILDREN; i++) {
if (n->children[i] != NULL) {
dll_append(q, new_jval_v(n->children[i]));
}
}
}
}
printf("}");
free_dllist(q);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment