PHP 数据结构 算法 三元组 Triplet

发布网友 发布时间:2022-04-23 12:12

我来回答

1个回答

热心网友 时间:2023-05-01 19:46

复制代码
代码如下:
<?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_mp($objTriplet->init(1,2,3));
echo
"<br/>";
echo
"get
1:";var_mp($objTriplet->get(1));
echo
"<br/>";
echo
"get
4:";var_mp($objTriplet->get(4));
echo
"<br/>";
//
false
echo
"put
3,4:";var_mp($objTriplet->put(3,4));
echo
"<br/>";
echo
"max:";var_mp($objTriplet->max());
echo
"<br/>";
echo
"min:";var_mp($objTriplet->min());
echo
"<br/>";
echo
"isAscending:";var_mp($objTriplet->isAscending());
echo
"<br/>";
echo
"isDescending:";var_mp($objTriplet->isDescending());
echo
"<br/>";
?>

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com