<?
class tree{
var $tree=array();
var $rootSign=array('and','or');
//var $leafSign=array('<','>','=','>=','<=');
var $leafSign=array('<','>','=');
function createTree($s){
$leafs=array();
$roots=array();
$tmp=explode(' ',$s) ;
for($i=0;$i<sizeof($tmp);$i++){
if(in_array($tmp[$i],$this->leafSign)){
$leaf=array($tmp[$i-1],$tmp[$i+1],$tmp[$i]);
array_push($leafs,$leaf);
}elseif(in_array($tmp[$i],$this->rootSign)){
array_push($roots,$tmp[$i]);
}
}
if(empty($roots)){
$this->tree=$leafs[0];
}else{
for($i=0;$i<sizeof($leafs);$i+=2){
$tree=array($leafs[$i],$leafs[$i+1],$roots[$i/2]);
}
//print_r($tree);
// echo "<br>";
$this->tree=$tree;
}
}
function tree($s){
$this->createTree($s);
}
function compareTree($T1,$T2){
if(is_array($T1[0])){
$tmp1=$this->compareTree($T1[0],$T2[0]);
$tmp2=$this->compareTree($T1[1],$T2[1]);
}else{
return $this->compareLeaf($T1,$T2);
}
if($T1[2]==$T2[2]){
if($T1[2]=='or'){
print_r($T1);
return $tmp1||$tmp2;
}
if($T1[2]=='and')
return $tmp1&&$tmp2;
}
if($T2[2]=='or'){
//print_r($tmp2);
return $tmp1||$tmp2;
}
return false;
}
function compareLeaf($L1,$L2){
if($L1[0]!=$L2[0])
return false;
if($L1[2]==$L2[2]){
return $this->compare($L1[2],$L1[1],$L2[1]);
}
if($L1[2]!="="&&$L2[2]!="="){
return false;
}
if($L1[2]=="="){
return !$this->compare($L1[2],$L1[1],$L2[1]);
}else{
return !$this->compare($L2[2],$L1[1],$L2[1]);
}
}
function compare($sign,$valr,$vall){
$tmp=$valr-$vall;
switch($sign){
case '<':
return $tmp<=0?true:false;
case '>':
return $tmp>=0?true:false;
case '=':
return $tmp==0?true:false;
/*
case '<=':
return $tmp<=0?true:false;
case '>=':
return $tmp>=0?true:false;
*/
}
}
function isSubSet($tree){
return $this->compareTree($this->tree,$tree);
}
}
function test($sA,$sB,$flag){
$tmpFlag=0;
$tree1=new tree($sA);
$tree2=new tree($sB);
if($tree1->isSubSet($tree2->tree)){
echo "A is subset of B";
$tmpFlag=1;
}else{
echo "A is not subset of B";
$tmpFlag=0;
}
echo "<br>";
echo $flag==$tmpFlag?"right":"<font color='red'>err</font>";
echo "<br>";
print_r($tree2->tree);
echo "<br>";
}
$treesA=array('age > 40','age > 18 and weight < 100','age > 30 and sex = 0','sex = 0');
$treesB=array('age > 18','age > 18 or weight < 100','age > 40 and sex = 0','sex < 0');
$flags=array(1,1,0,0);
while($treeA=array_shift($treesA)){
$treeB=array_shift($treesB);
$flag=array_shift($flags);
test($treeA,$treeB,$flag);
}