判断多个时间段是否重合的算法

php代码实现如下:

<?php
header('Content-Type:text/html;charset=utf-8');
class date_coincidence
{
    
    private $date_data;
    private $top;
    private $flag;
    private $queue;
    private $coincidence;
    
    public function __construct($date_data)
    {
        $this->date_data = array_map(array(__CLASS__, 'str_to_unixtime'), $date_data);
        $this->top = 0;
        $this->flag = 0;
        $this->queue = array();
        $this->coincidence = array();
        $this->comb(0, count($date_data), 2);
        if($this->flag == 1)
        {
            echo '以上时间段存在重合,重合的时间段为<hr/>';
            $this->coincidence = array_map(array(__CLASS__, 'unixtime_to_str'), $this->coincidence);
            foreach($this->coincidence as $v)
            {
                echo $v[0]['sd'].' 至 '.    $v[0]['ed'].'<br/>';
                echo $v[1]['sd'].' 至 '.    $v[1]['ed'].'<br/>';
                echo '<hr/>';
            }    
        }
        else
        {
            echo '以上时间段均不重合';    
        }
    }
    
    private static function str_to_unixtime($value)
    {
        $result = array('sd'=>strtotime($value['sd']), 'ed'=>strtotime($value['ed']));
        return $result;    
    }
    
    private static function unixtime_to_str($value)
    {
        $result = array(
                                        array('sd'=>date('Y-m-d', $value[0]['sd']), 'ed'=>date('Y-m-d', $value[0]['ed'])),
                                        array('sd'=>date('Y-m-d', $value[1]['sd']), 'ed'=>date('Y-m-d', $value[1]['ed']))
        );
        return $result;    
    }
    
    private function comb($s, $n, $m)
    {
        if ($s > $n)
        {
            return;
        }
        
        if ($this->top == $m)
        {
/*            for ($i = 0; $i < $m; $i++)
            {
                var_dump($this->queue[$i]);
            }*/
            if(($this->queue[0]['sd'] < $this->queue[1]['ed']) && ($this->queue[0]['ed'] > $this->queue[1]['sd']))
            {
                $this->flag = 1;
                array_push($this->coincidence, array($this->queue[0], $this->queue[1]));
            }
            //echo '<hr/>';
            return;
        }
        
        $this->queue[$this->top++] = empty($this->date_data[$s])?'':$this->date_data[$s];
        $this->comb($s+1, $n, $m);
        $this->top--;
        $this->comb($s+1, $n, $m);
    }
    
    private function execute($n, $A, $B, $C)
    {

    }
}

function main()
{
    $date_data = array(
        array('sd'=>'2014-01-01', 'ed'=>'2014-03-01'),
        array('sd'=>'2014-04-01', 'ed'=>'2014-05-01'),
        array('sd'=>'2014-05-01', 'ed'=>'2014-08-11'),
        array('sd'=>'2014-08-02', 'ed'=>'2014-09-01'),
        array('sd'=>'2014-08-01', 'ed'=>'2014-09-02')
    );
    new date_coincidence($date_data);
    return 0;    
}

main();


你可能感兴趣的:(PHP,算法,多个时间段,重合)