PHP data structure algorithm triple Triplet

  • 2020-05-09 18:20:54
  • OfStack

 
<?php 
/** 
* 3 tuples  Triplet 
* 
*/ 
class Triplet 
{ 
private $_data = null; 
//  Initialize the 3 tuples  
public function init($val1,$val2,$val3) 
{ 
$this->_data[0] = $val1; 
$this->_data[1] = $val2; 
$this->_data[2] = $val3; 
return true; 
} 
//  The destruction 3 tuples  
public function destroy() 
{ 
unset($this->_data); 
return true; 
} 
//  Returns the first $key The value of the  
public function get($key) 
{ 
if($key < 1 || $key > 3) return false; 
return $this->_data[$key - 1]; 
} 
//  Set up the first $key The value of the yuan $val 
public function put($key,$val) 
{ 
if($key < 1 || $key > 3) return false; 
$this->_data[$key - 1] = $val; 
return true; 
} 
//  Whether to sort in ascending order  
public function isAscending() 
{ 
return ($this->_data[0] <= $this->_data[1]) && ($this->_data[1] <= $this->_data[2]); 
} 
//  Whether to sort in descending order  
public function isDescending() 
{ 
return ($this->_data[0] >= $this->_data[1]) && ($this->_data[1] >= $this->_data[2]); 
} 
//  Get the maximum  
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]; 
} 
//  Get the minimum  
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/>"; 
?> 

Related articles: