Comment Re:sounds great (Score 1) 375
Essentially I made a class to represent a node that represents a dot of the pattern. That node can have direct edges to other nodes. Additionally it can have a set of conditional edges, which are the edges that can only be traversed if "intervening" nodes have already been used (visited) earlier on any given path (walk). The walk() method basically traverses all edges and any available conditional edges of the current node, then continues the walk recursively for each node being visited. The whole time a global counter gets updated, counting the total paths.
class Node{
private $visited = false;
private $name;
private $edges = array();
private $condEdges = array();
public function __construct($name){
$this->name = $name;
}
public function addEdge($node){
$this->edges[] = $node;
}
public function addCondEdge($targetNode,$skipNode){
$this->condEdges[] = array('target'=>$targetNode, 'skip'=>$skipNode);
}
public function visit(){
$this->visited = true;
}
public function isVisited(){
return $this->visited;
}
public function unVisit(){
$this->visited = false;
}
public function walk($steps,$path=''){
$this->visit();
$path
if ($steps > 0){
foreach ($this->condEdges as $condEdge){
if ($condEdge['skip']->isVisited() and (!$condEdge['target']->isVisited()))
$condEdge['target']->walk($steps-1,$path);
}
foreach ($this->edges as $edgeNode){
if (!$edgeNode->isVisited())
$edgeNode->walk($steps-1,$path);
}
}
else{
$GLOBALS['count']++;
echo "#{$GLOBALS['count']}: path: $path\n";
}
$this->unVisit();
}
}
Then I build the actual set of nodes making up the Android dots, e.g. (if numbering the dots left to right, top to bottom 1-9):
$node1 = new Node('1');
$node2 = new Node('2');
$node3 = new Node('3');
$node4 = new Node('4');
$node5 = new Node('5');
$node6 = new Node('6');
$node7 = new Node('7');
$node8 = new Node('8');
$node9 = new Node('9');
$node1->addEdge($node2);
$node1->addCondEdge($node3, $node2);
$node1->addEdge($node4);
$node1->addEdge($node5);
$node1->addEdge($node6);
$node1->addCondEdge($node7, $node4);
$node1->addEdge($node8);
$node1->addCondEdge($node9, $node5);
.
.
.
Then put the nodes together for convenience so we can loop through all possibilities:
$graph = array();
for ($i=1; $i<=9; $i++){
$node = "node$i";
$graph[] = $$node;
}
Then we walk through all possibilities:
$GLOBALS['count'] = 0;
for ($i=3; $i<=8; $i++){
foreach ($graph as $node){
$node->walk($i);
echo "=============\n";
}
}