求數字組合演算法解決方案

來源:互聯網
上載者: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));
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.