欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

PHP 数据结构 算法 三元组 Triplet

程序员文章站 2023-09-09 19:01:11
复制代码 代码如下:
复制代码 代码如下:

<?php
/**
* 三元组 triplet
*
*/
class triplet
{
private $_data = null;
// 初始化三元组
public function init($val1,$val2,$val3)
{
$this->_data[0] = $val1;
$this->_data[1] = $val2;
$this->_data[2] = $val3;
return true;
}
// 销毁三元组
public function destroy()
{
unset($this->_data);
return true;
}
// 返回第$key的值
public function get($key)
{
if($key < 1 || $key > 3) return false;
return $this->_data[$key - 1];
}
// 设置第$key元的值为$val
public function put($key,$val)
{
if($key < 1 || $key > 3) return false;
$this->_data[$key - 1] = $val;
return true;
}
// 是否按升序排序
public function isascending()
{
return ($this->_data[0] <= $this->_data[1]) && ($this->_data[1] <= $this->_data[2]);
}
// 是否按降序排序
public function isdescending()
{
return ($this->_data[0] >= $this->_data[1]) && ($this->_data[1] >= $this->_data[2]);
}
// 获取最大值
public function max()
{
return ($this->_data[0] >= $this->_data[1])? ($this->_data[0] >= $this->_data[2])? $this->_data[0] : $this->_data[2] : ($this->_data[1] >= $this->_data[2])? $this->_data[1] : $this->_data[2];
}
// 获取最小值
public function min()
{
return ($this->_data[0] <= $this->_data[1])? ($this->_data[0] <= $this->_data[2])? $this->_data[0] : $this->_data[2] : ($this->_data[1] <= $this->_data[2])? $this->_data[1] : $this->_data[2];
}
}
//
$objtriplet = new triplet();
echo "init:";var_dump($objtriplet->init(1,2,3)); echo "<br/>";
echo "get 1:";var_dump($objtriplet->get(1)); echo "<br/>";
echo "get 4:";var_dump($objtriplet->get(4)); echo "<br/>"; // false
echo "put 3,4:";var_dump($objtriplet->put(3,4)); echo "<br/>";
echo "max:";var_dump($objtriplet->max()); echo "<br/>";
echo "min:";var_dump($objtriplet->min()); echo "<br/>";
echo "isascending:";var_dump($objtriplet->isascending()); echo "<br/>";
echo "isdescending:";var_dump($objtriplet->isdescending()); echo "<br/>";
?>