Created
August 8, 2021 21:11
-
-
Save adevesa/2238ad0ba869223bdf023dfec28c4667 to your computer and use it in GitHub Desktop.
Exercise Stair with Steps
This file contains hidden or 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 Tree { | |
/** | |
* @var Node[] | |
*/ | |
public $nodes; | |
/** | |
* @var Node | |
*/ | |
public $root; | |
/** | |
* @var integer | |
*/ | |
public $goal; | |
public function __construct(int $goal) | |
{ | |
$this->root = new Node(0); | |
$this->nodes = []; | |
$this->goal = $goal; | |
$this->fillNodes(); | |
} | |
public function fillNodes(): void | |
{ | |
$nodesToAnalyze = $this->root->bornChildren(); | |
$this->nodes = array_merge($this->nodes, $nodesToAnalyze); | |
while(sizeof($nodesToAnalyze) > 0){ | |
if($nodesToAnalyze[0]->canHaveChidren($this->goal)){ | |
$nodesBornt = $nodesToAnalyze[0]->bornChildren(); | |
$this->nodes = array_merge($this->nodes, $nodesBornt); | |
$nodesToAnalyze = array_merge($nodesToAnalyze, $nodesBornt); | |
} | |
array_shift($nodesToAnalyze); | |
} | |
} | |
public function nodesArrived(): int | |
{ | |
$count = 0; | |
foreach ($this->nodes as $node) | |
if($node->hasArrivedTo($this->goal)) $count++; | |
return $count; | |
} | |
} | |
class Node { | |
/** | |
* @var integer | |
*/ | |
public $value; | |
/** | |
* @var Node[] | |
*/ | |
public $children; | |
/** | |
* @param Node | |
*/ | |
public $parent; | |
public function __construct(int $value, ?Node $parent = null) | |
{ | |
$this->value = $value; | |
$this->children = []; | |
$this->parent = $parent; | |
} | |
public function addChild(Node $child) | |
{ | |
if(sizeof($this->children) < 2 ) | |
$this->children[] = $child; | |
else | |
throw new Exception("Cannot add more than 2 childs to the node."); | |
} | |
public function canHaveChidren(int $value) | |
{ | |
return !$this->hasArrivedTo($value) && !$this->hasPass($value); | |
} | |
public function bornChildren() | |
{ | |
$this->addChild(new Node(1, $this)); | |
$this->addChild(new Node(2, $this)); | |
return $this->children; | |
} | |
public function inheritedValue() | |
{ | |
if(!$this->parent) return $this->value; | |
return $this->value + $this->parent->inheritedValue(); | |
} | |
public function hasArrivedTo(int $value) | |
{ | |
return $this->inheritedValue() === $value; | |
} | |
public function hasPass(int $value) | |
{ | |
return $this->inheritedValue() > $value; | |
} | |
} | |
$tree = new Tree(15); | |
echo $tree->nodesArrived(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment