日能研の広告の問題を解く記事がpythonとcとgoで上がっていたので・・・
phpで実装しようかと。
まず、pythonのitertools.permutations()の部分を実装
permutations.php
<?php
function permutations($list, $length, $case=[], $results=[])
{
$list_count = count($list);
if ($length>$list_count){ // エラー
return [];
}
if ($length===0 || $list_count===0){ // 探索終了
$results[] = $case;
return $results;
}
for ($i=0; $i<$list_count; $i++){
$target = $list; // 初期状態に戻す
array_push($case, $target[$i]); // 値を追加
unset($target[$i]); // リストから値を削除
$target = array_values($target); // 添字再設定
// 次の桁を探索
$results = permutations($target, $length-1, $case, $results);
array_pop($case); // 値を削除
}
return $results;
}
すべての組み合わせが取得できれば、あとはチェック。
ちょっと冗長的なところもありますが。
日能研201811.php
<?php
require('./permutations.php');
$results = permutations([1,2,3,4,5,6], 6);
foreach($results as $case){
$check = true;
for ($i=0, $v=0; $i<6; $i++, $v *= 10){
$v += $case[$i];
if ( $v % ($i+1) !== 0 ){
$check = false;
break;
}
}
if ($check){
print(implode(',', $case) . "\n");
}
}
pythonいいなぁ