[php]数据结构&算法(PHP描述) 三元组 Triplet

1 <?php
2 /**
3 * 三元组 Triplet
4 *
5 */
6 class Triplet
7 {
8 private$_data=null;
9
10 // 初始化三元组
11 publicfunction init($val1,$val2,$val3)
12 {
13 $this->_data[0] =$val1;
14 $this->_data[1] =$val2;
15 $this->_data[2] =$val3;
16 returntrue;
17 }
18
19 // 销毁三元组
20 publicfunction destroy()
21 {
22 unset($this->_data);
23 returntrue;
24 }
25
26 // 返回第$key的值
27 publicfunction get($key)
28 {
29 if($key<1||$key>3) returnfalse;
30 return$this->_data[$key-1];
31 }
32
33 // 设置第$key元的值为$val
34 publicfunction put($key,$val)
35 {
36 if($key<1||$key>3) returnfalse;
37 $this->_data[$key-1] =$val;
38 returntrue;
39 }
40
41 // 是否按升序排序
42 publicfunction isAscending()
43 {
44 return ($this->_data[0] <=$this->_data[1]) && ($this->_data[1] <=$this->_data[2]);
45 }
46
47 // 是否按降序排序
48 publicfunction isDescending()
49 {
50 return ($this->_data[0] >=$this->_data[1]) && ($this->_data[1] >=$this->_data[2]);
51 }
52
53 // 获取最大值
54 publicfunctionmax()
55 {
56 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];
57 }
58
59 // 获取最小值
60 publicfunctionmin()
61 {
62 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];
63 }
64 }
65
66 //
67 $objTriplet=new Triplet();
68 echo"init:";var_dump($objTriplet->init(1,2,3)); echo"<br/>";
69
70 echo"get 1:";var_dump($objTriplet->get(1)); echo"<br/>";
71 echo"get 4:";var_dump($objTriplet->get(4)); echo"<br/>"; // false
72 echo"put 3,4:";var_dump($objTriplet->put(3,4)); echo"<br/>";
73
74 echo"max:";var_dump($objTriplet->max()); echo"<br/>";
75 echo"min:";var_dump($objTriplet->min()); echo"<br/>";
76
77 echo"isAscending:";var_dump($objTriplet->isAscending()); echo"<br/>";
78 echo"isDescending:";var_dump($objTriplet->isDescending()); echo"<br/>";
79 ?>

posted on 2011-07-02 22:04  bluefrog  阅读(930)  评论(0编辑  收藏  举报