| 
            Last change
 on this file since fae93a40 was             7640ff5, checked in by Alvin Zhang <alvin.zhang@…>, 4 months ago           | 
        
        
          | 
             
add graph example for modules proposal 
 
           | 
        
        
          
            
              - 
Property                 mode
 set to                 
100644
               
             
           | 
        
        
          | 
            File size:
            1.1 KB
           | 
        
      
      
| Rev | Line |   | 
|---|
| [7640ff5] | 1 | module;
 | 
|---|
 | 2 | 
 | 
|---|
 | 3 | import graph/node;
 | 
|---|
 | 4 | import graph/edge;
 | 
|---|
 | 5 | 
 | 
|---|
 | 6 | import stdlib;
 | 
|---|
 | 7 | 
 | 
|---|
 | 8 | export struct Graph {
 | 
|---|
 | 9 |     struct Node *nodes;
 | 
|---|
 | 10 |     struct Edge *edges;
 | 
|---|
 | 11 |     int num_nodes;
 | 
|---|
 | 12 |     int num_edges;
 | 
|---|
 | 13 | };
 | 
|---|
 | 14 | 
 | 
|---|
 | 15 | export struct Graph create_rand_graph(int num_nodes, int num_edges) {
 | 
|---|
 | 16 |     struct Graph g;
 | 
|---|
 | 17 |     g.num_nodes = num_nodes;
 | 
|---|
 | 18 |     g.num_edges = num_edges;
 | 
|---|
 | 19 |     g.nodes = (struct Node *) calloc(num_nodes, sizeof(struct Node));
 | 
|---|
 | 20 |     g.edges = (struct Edge *) calloc(num_edges, * sizeof(struct Edge));
 | 
|---|
 | 21 |     for (int i=0; i<num_edges; ++i) {
 | 
|---|
 | 22 |         struct Node *first = grab_random_node(&g), *second = grab_random_node(&g);
 | 
|---|
 | 23 |         g.edges[i] = create_edge(first, second);
 | 
|---|
 | 24 |         add_edge(first, &g.edges[i]);
 | 
|---|
 | 25 |         add_edge(second, &g.edges[i]);
 | 
|---|
 | 26 |     }
 | 
|---|
 | 27 |     return g;
 | 
|---|
 | 28 | }
 | 
|---|
 | 29 | 
 | 
|---|
 | 30 | export struct Node *grab_random_node(struct Graph *g) {
 | 
|---|
 | 31 |     return &g->nodes[rand() % g->num_nodes];
 | 
|---|
 | 32 | }
 | 
|---|
 | 33 | 
 | 
|---|
 | 34 | const int max_steps_to_walk = 1000;
 | 
|---|
 | 35 | export int path_found(struct Node *first, struct Node *second) {
 | 
|---|
 | 36 |     return random_search(first, second, max_steps_to_walk);
 | 
|---|
 | 37 | }
 | 
|---|
 | 38 | 
 | 
|---|
 | 39 | export int destroy_graph(struct Graph *g) {
 | 
|---|
 | 40 |     free(g->nodes);
 | 
|---|
 | 41 |     free(g->edges);
 | 
|---|
 | 42 |     return 0;
 | 
|---|
 | 43 | }
 | 
|---|
       
      
  Note:
 See   
TracBrowser
 for help on using the repository browser.