求數字組合演算法解決方案
來源:互聯網
上載者:User
求數字組合演算法
假設有4個數字
1,2,3,4
要求其中三個數位排列,但不能重複。
例如組合:123,124,134,234。
其中 123 的組合和213,312,321,132,231 的組合都是一樣的。
怎麼實現?小弟菜鳥,線上等,謝謝!
------解決方案--------------------
上面有錯
for($i=1;$i <=5-2;$i++){
for($j=$i+1;$j <=5-1;$j++){
for($k=$j+1;$k <=5;$k++){
echo "$i,$j,$k
";
}
}
}
------解決方案--------------------
/**
* 函數 combination
* 功能 m取n的組合函數
* 參數
* $ar 數組,未經處理資料
* $num 數值,每個組合的元素個數
**/
if(! function_exists( 'combination ')):
function combination($ar, $num) {
$control = range(0, $num-1);
$k = false;
$total = count($ar);
while($control[0] < $total-($num-1)) {
$t = array();
for($i=0; $i <$num; $i++) $t[] = $ar[$control[$i]];
$r[] = $t;
for($i=$num-1; $i> =0; $i--) {
$control[$i]++;
for($j=$i; $j <$num-1; $j++) $control[$j+1] = $control[$j]+1;
if($control[$i] < $total-($num-$i-1)) break;
}
}
return $r;
}
endif;
/** 樣本 **/
print_r(combination(array(1,2,3,4,5), 3));