Created
February 7, 2017 05:30
-
-
Save Mo3g4u/ec8674d04e750e7247cc8416bac11569 to your computer and use it in GitHub Desktop.
組み合わせ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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