Skip to content

Instantly share code, notes, and snippets.

@cebe
Last active August 29, 2015 14:01
Show Gist options
  • Save cebe/d325a02b3b2d31ac3a1e to your computer and use it in GitHub Desktop.
Save cebe/d325a02b3b2d31ac3a1e to your computer and use it in GitHub Desktop.
Create random graphs with php and graphiz
<?php
$maxN = 10;
$maxE = 20;
// generate random edges
$e = [];
for($n = 1; $n <= $maxE; $n++) {
$e[] = [rand(1, $maxN), rand(1, $maxN)];
}
// remove duplicates and self-loops
$dup = [];
foreach($e as $i => $v) {
if ($v[0] == $v[1]) {
unset($e[$i]);
}
$d = $v[0].':'.$v[1];
if (isset($dup[$d])) {
unset($e[$i]);
} else {
$dup[$d] = true;
}
}
$graph = <<<EOF
digraph example {
rankdir=LR;
graph [ dpi = 300 ];
size="8,5"
node [shape = circle];
EOF;
foreach($e as $edge) {
list($from, $to) = $edge;
$graph .= "$from -> $to;\n";
}
$graph .= "}\n";
echo $graph;
@cebe
Copy link
Author

cebe commented May 13, 2014

Usage:

php randgraph.php > graph.dot
dot -O -Tpng graph.dot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment