source: doc/proposals/modules-alvin/examples/graph/4_impl/graph__impl.c

Last change on this file was 7640ff5, checked in by Alvin Zhang <alvin.zhang@…>, 2 months ago

add graph example for modules proposal

  • Property mode set to 100644
File size: 1.6 KB
Line 
1#include "graph__export.h"
2
3#include "graph/node__export.h"
4#include "graph/edge__export.h"
5
6#include <stdlib__export.h>
7
8// move constants to top
9const int graph$$max_steps_to_walk = 1000;
10
11struct graph$$Graph$$shell graph$$create_rand_graph(int num_nodes, int num_edges) {
12 struct graph$$Graph$$shell g;
13 (*(struct graph$$Graph*)&g).num_nodes = num_nodes;
14 (*(struct graph$$Graph*)&g).num_edges = num_edges;
15 (*(struct graph$$Graph*)&g).nodes = (struct graph$node$$Node$$shell *) calloc(num_nodes, sizeof(struct graph$node$$Node$$shell));
16 (*(struct graph$$Graph*)&g).edges = (struct graph$edge$$Edge$$shell *) calloc(num_edges, sizeof(struct graph$edge$$Edge$$shell));
17 for (int i=0; i<num_edges; ++i) {
18 struct graph$node$$Node$$shell *first = graph$$grab_random_node(&g), *second = graph$$grab_random_node(&g);
19 (*(struct graph$$Graph*)&g).edges[i] = graph$edge$$create_edge(first, second);
20 graph$node$$add_edge(first, &(*(struct graph$$Graph*)&g).edges[i]);
21 graph$node$$add_edge(second, &(*(struct graph$$Graph*)&g).edges[i]);
22 }
23 return g;
24}
25
26struct graph$node$$Node$$shell *graph$$grab_random_node(struct graph$$Graph$$shell *g) {
27 return &((struct graph$$Graph*)g)->nodes[rand() % ((struct graph$$Graph*)g)->num_nodes];
28}
29
30int graph$$path_found(struct graph$node$$Node$$shell *first, struct graph$node$$Node$$shell *second) {
31 return graph$node$$random_search(first, second, graph$$max_steps_to_walk);
32}
33
34int graph$$destroy_graph(struct graph$$Graph$$shell *g) {
35 free(((struct graph$$Graph*)g)->nodes);
36 free(((struct graph$$Graph*)g)->edges);
37 return 0;
38}
Note: See TracBrowser for help on using the repository browser.