calabrothers / php-ds-tree
PHP 树支持
1.0.0
2020-01-19 23:08 UTC
Requires
- php-ds/php-ds: dev-master
Requires (Dev)
- phpunit/phpunit: ^8.5
This package is auto-updated.
Last update: 2024-09-20 09:43:45 UTC
README
PHP 树支持
一个用于支持位掩码操作的类。
安装
composer require calabrothers/php-ds-tree
测试
composer install
composer test
树库
我们可以引入以下相关信息来讨论库功能
与其他节点的关系
对于这个集合中的每一个,定义一个包括自身参数的额外集合,因此
静态函数
作为 Ds\Deque 对象,树库提供以下操作
- apply (使用可调用的函数更改节点值)
- filter (根据指定的条件选择节点子集的可调用函数)
- map (使用可调用函数评估节点值并计算结果)
这些基本操作作为静态函数提供,并作用于给定的节点集。一个魔术函数提供了访问先前定义的所有集合的方法。
示例:让我们计算
y = 2 x sum( Descendants(A) )
首先,我们需要获取一个给定的节点集 Descendants(A),然后应用一个 map 来加倍值。最后,我们应该求和结果向量的元素。
// Let build some tree...
/*
A(1)
/ \
B(2) C(3)
/ \
D(4) E(5)
*/
$oA = new TreeNode(1);
$oB = new TreeNode(2);
$oC = new TreeNode(3);
$oD = new TreeNode(4);
$oE = new TreeNode(5);
连接节点以形成树
// Connects the nodes
$oC->attachChild($oD);
$oC->attachChild($oE);
$oA->attachChild($oB);
$oA->attachChild($oC);
计算结果
// Compute 2 x Value, forall the Descendants(A)
$aValue = TreeNode::mapSet(
$oA->getDescendants(),
function ($oValue) {
return 2 * $oValue;
}
);
echo $aValue->sum()."\n"; // 28
参考相同的树,例如,我们可以获取具有偶数值的节点列表如下
// Get nodes having even value
$aEven = TreeNode::filterSet(
$oA->getNodes(),
function ($oValue) {
return $oValue % 2 == 0;
}
);
echo "(".$aEven[0]->getValue().",".$aEven[1]->getValue().")"; // (2,4)
树构建器
库提供了一个方便的类,用于帮助构建树。
构建器需要一个可调用的函数,负责构建新节点。例如,考虑一个整数值的树
$oTreeC = new TreeBuilder(
function (int $nNumber) : int {
return $nNumber;
}
);
每次调用 begin() 函数时,都会添加一个新节点,并将 begin() 函数的参数传递给 TreeBuilder 构造函数中指定的可调用函数。
$oTreeC
->begin(1)
->begin(2)
->end()
->begin(3)
->begin(4)
->end()
->begin(5)
->end()
->end()
->end();
所有具有适当 __toString() 方法的类型都可以看到节点值。例如,在这种情况下
echo $oTree;
// Result:
┌1
└────2
└────3
└────4
└────5
当与自定义节点类结合使用时,TreeBuilder 非常有趣,例如,让我们考虑构建一个具有以下类对象的节点作为节点的树
class TreeNodeExample {
public $nX;
public $szY;
public function __construct(int $nX, string $szY) {
$this->nX = $nX;
$this->szY = $szY;
}
public function myMultiply(int $nZ) {
$this->nX *= $nZ;
$this->szY = implode("+", array_fill(0, $nZ,$this->szY));
}
public function __toString():string {
return "($this->nX|$this->szY)";
}
}
然后我们可以使用 TreeBuilder 如下
$oTreeC = new TreeBuilder(
function (int $nX, string $szY) : TreeNodeExample {
return new TreeNodeExample($nX, $szY);
}
);
$oTreeC
->begin(1, 'one')
->begin(2, 'two')
->end()
->begin(3, 'three')
->begin(4, 'four')
->myMultiply(2) // This will call the method of TreeNodeExample! :)
->end()
->begin(5, 'five')
->myMultiply(3)
->end()
->end()
->end();
echo $oTreeC;
┌(1|one)
└────(2|two)
└────(3|three)
└────(8|four+four)
└────(15|five+five+five)
备注
我强烈建议使用 PHP Ds 扩展而不是其等效的 Php 版本。有关更多信息,请参阅 https://github.com/php-ds/ext-ds
致谢
支持高质量的代码
许可证
MIT 许可证 (MIT)。有关更多信息,请参阅 LICENSE