头像

php排列组合函数(无重复)

发布时间:2018-09-13 11:37:26

发布作者:admin

3661

例1:
        /**
	 * 無重複排列組合
	 * @Author   MAX
	 * @DateTime 2018-09-07T16:28:40+0800
	 * @param    Array                   $arr 需要排列組合的數組
	 * @param    Number                   $m   每几個一組
	 * @param    [Array]                  $push   添加到組合數組裏
	 * @return   Array                        組合好的數組
	 */

	function getCombinationToString($arr, $m, $push=null) {
		$rst = array();
		for($i = 0; $i < pow(2, count($arr)); $i++) {
			$a = 0;
			$b = array();
			for($j = 0; $j < count($arr); $j++) {
				if($i >> $j & 1) {
					$a++;
					array_push($b, $arr[$j]);
				}
			}
			if($a == $m) {
				if(!is_null($push)){
					if(is_string($push)){
						$b = array_unshift($b, $push);
					}else{
						$b = array_merge($push, $b);
					}
				}
				$rst[] = $b;
			}
		}
		return $rst;
	}
例2:
	function getCombinationToString($arr, $m)
	{
	    $result = array();
	    if ($m ==1)
	    {
	       return $arr;
	    }
	    
	    if ($m == count($arr))
	    {
	        $result[] = implode(',' , $arr);
	        return $result;
	    }
	        
	    $temp_firstelement = $arr[0];
	    unset($arr[0]);
	    $arr = array_values($arr);
	    $temp_list1 = $this->getCombinationToString($arr, ($m-1));
	    
	    foreach ($temp_list1 as $s)
	    {
	        $s = $temp_firstelement.','.$s;
	        $result[] = $s;
	    }
	    unset($temp_list1);

	    $temp_list2 = $this->getCombinationToString($arr, $m);
	    foreach ($temp_list2 as $s)
	    {
	        $result[] = $s;
	    }    
	    unset($temp_list2);
	    
	    return $result;
	}


相关文章:
  1. CentOS7 安装 Pure-ftpd
  2. apache 设置禁止IP直接访问
  3. TortoiseGit提交一直显示请稍候
  4. node.js 进程守护forever