Skip to content

Instantly share code, notes, and snippets.

@Mo3g4u
Created February 7, 2017 05:30
Show Gist options
  • Save Mo3g4u/ec8674d04e750e7247cc8416bac11569 to your computer and use it in GitHub Desktop.
Save Mo3g4u/ec8674d04e750e7247cc8416bac11569 to your computer and use it in GitHub Desktop.
組み合わせ
<?php
function getCpattern( $source, $m ){
$n = sizeof($source);
return ptn( $source, $n, [], 0, $n-$m+1 );
}
// 再帰
function ptn( $source, $n, $subset, $begin, $end ){
$p = [];
for( $i = $begin; $i<$end; $i++){
$tmp =array_merge( $subset, (array)$source[$i] );
if( $end+1 <= $n ){
$p = array_merge($p , ptn( $source, $n, $tmp, $i+1, $end+1 ) );
}else{
array_push( $p, $tmp );
}
}
return $p;
}
$total = 200; // 合計値
$source = [ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26 ]; // 対象配列
$m = 10; // 選ぶ個数
$p = getCPattern( $source, $m ); //返ってくるのは全ての組み合わせを格納した配列
// csvっぽく出力
foreach ($p as $set){
if(array_sum($set) == $total){
echo implode(',', $set) . "\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment