-
-
Save itsbth/82f8d9f58798e960b9e2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Node | |
{ | |
public $part; | |
public $map; | |
public $end; | |
public $nid; | |
private static $count = 0; | |
public static function fold(Node $root) | |
{ | |
$nm = array(); | |
foreach ($root->children() as $child) | |
{ | |
Node::fold($child); | |
$children = $child->children(); | |
if (count($children) === 1 && !$child->end) | |
{ | |
$str = $child->part . $children[0]->part; | |
$child = new Node($str); | |
$child->map = $children[0]->map; | |
$child->end = $children[0]->end; | |
} | |
$nm[$child->part] = $child; | |
} | |
ksort($nm); | |
$root->map = $nm; | |
} | |
function __construct($part) | |
{ | |
$this->part = $part; | |
$this->map = array(); | |
$this->end = false; | |
$this->nid = Node::$count++; | |
} | |
public function add($str) | |
{ | |
if (strlen($str) === 0) | |
{ | |
$this->end = true; | |
return $this; | |
} | |
$char = $str[0]; | |
$rest = substr($str, 1); | |
if(!isset($this->map[$char])) $this->map[$char] = new Node($char); | |
return $this->map[$char]->add($rest); | |
} | |
public function children() | |
{ | |
return array_values($this->map); | |
} | |
public function id() | |
{ | |
return "node" . $this->nid; | |
} | |
} | |
$root = new Node(''); | |
$funcs = get_defined_functions(); | |
$internal = $funcs['internal']; | |
foreach ($internal as $func) { | |
$root->add($func); | |
} | |
Node::fold($root); | |
function recurse(Node $node) | |
{ | |
$shape = $node->end ? 'diamond' : 'oval'; | |
if ($node->part != '') echo "\t{$node->id()} [label = \"{$node->part}\", shape = {$shape}]\n"; | |
foreach ($node->children() as $child) { | |
if ($node->part != '' && $child->part != '') echo "\t{$node->id()} -> {$child->id()}\n"; | |
recurse($child); | |
} | |
} | |
echo "digraph funcs {\n"; | |
recurse($root); | |
echo "}\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment