LoginSignup
3
0

More than 5 years have passed since last update.

日能研の問題をphpで解いてみた(2018/11)

Last updated at Posted at 2018-11-17

日能研の広告の問題を解く記事が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いいなぁ

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0