Skip to content

Instantly share code, notes, and snippets.

@submachine
Created October 9, 2012 00:37
Show Gist options
  • Save submachine/3855851 to your computer and use it in GitHub Desktop.
Save submachine/3855851 to your computer and use it in GitHub Desktop.
A quick-n-dirty random DAG generator
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* http://stackoverflow.com/q/12790337/274261 */
/* Generates random DAGs. The key is to 'rank' the nodes, and
only draw edges from lower ranked nodes to higher ranked ones. */
/* Nodes/Rank: How 'fat' the DAG should be. */
#define MIN_PER_RANK 1
#define MAX_PER_RANK 5
/* Ranks: How 'tall' the DAG should be. */
#define MIN_RANKS 3
#define MAX_RANKS 5
/* Chance of having an Edge. */
#define PERCENT 30
int main (void)
{
int i, j, k, nodes = 0;
srand (time (NULL));
int ranks = MIN_RANKS
+ (rand () % (MAX_RANKS - MIN_RANKS + 1));
printf ("digraph {\n");
for (i = 0; i < ranks; i++)
{
/* New nodes of 'higher' rank than all nodes generated till now. */
int new_nodes = MIN_PER_RANK
+ (rand () % (MAX_PER_RANK - MIN_PER_RANK + 1));
/* Edges from old nodes ('nodes') to new ones ('new_nodes'). */
for (j = 0; j < nodes; j++)
for (k = 0; k < new_nodes; k++)
if ( (rand () % 100) < PERCENT)
printf (" %d -> %d;\n", j, k + nodes); /* An Edge. */
nodes += new_nodes; /* Accumulate into old node set. */
}
printf ("}\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment