検索
ホームページバックエンド開発PHPチュートリアルPHP を使用して、7 つの数値 (1、2、3、4、5、6、7) の配列から 5 つの数値の一意の組み合わせをすべて生成するにはどうすればよいですか?

How can I generate all unique combinations of 5 numbers from an array of 7 numbers (1, 2, 3, 4, 5, 6, 7) using PHP?

PHP 配列の組み合わせ

7 つの数値 (1、2、3、4、5、6、7) の配列が与えられます。 。目標は、その配列から 5 つの数字の可能な組み合わせをすべて見つけることです。各組み合わせは一意でなければなりません。つまり、重複は許可されません。たとえば、(1,2,3,4,5) と (5,4,3,2,1) は同じ組み合わせとみなされます。

Solution

考えられる解決策の 1 つは、Combinations クラスを使用することです。これは、Iterator インターフェイスを実装し、指定された数値のすべての可能な組み合わせを反復処理する方法を提供します。その仕組みは次のとおりです:

class Combinations implements Iterator
{
    protected $c = null; // Combination of numbers
    protected $s = null; // Source array
    protected $n = 0; // Number of elements in the array
    protected $k = 0; // Number of elements in each combination
    protected $pos = 0; // Current position of the iterator

    function __construct($s, $k) {
        // Initialize the class properties
        if(is_array($s)) {
            $this->s = array_values($s);
            $this->n = count($this->s);
        } else {
            $this->s = (string) $s;
            $this->n = strlen($this->s);
        }
        $this->k = $k;
        $this->rewind();
    }

    // Return the current key
    function key() {
        return $this->pos;
    }

    // Return the current value
    function current() {
        $r = array();
        for($i = 0; $i k; $i++)
            $r[] = $this->s[$this->c[$i]];
        return is_array($this->s) ? $r : implode('', $r);
    }

    // Move to the next combination
    function next() {
        if($this->_next())
            $this->pos++;
        else
            $this->pos = -1;
    }

    // Rewind to the first combination
    function rewind() {
        $this->c = range(0, $this->k);
        $this->pos = 0;
    }

    // Check if the iterator is valid (at a valid position)
    function valid() {
        return $this->pos >= 0;
    }

    // Move to the next combination (internal function)
    protected function _next() {
        $i = $this->k - 1;
        while ($i >= 0 && $this->c[$i] == $this->n - $this->k + $i)
            $i--;
        if($i c[$i]++;
        while($i++ k - 1)
            $this->c[$i] = $this->c[$i - 1] + 1;
        return true;
    }
}

// Create a Combinations object for the given array and number of elements per combination
$combinations = new Combinations("1234567", 5);

// Iterate over all possible combinations and print them out
foreach($combinations as $substring)
    echo $substring, ' ';

このコードは次の出力を生成します:

12345 12346 12347 12356 12357 12367 12456 12457 12467 12567 13456 13457 13467 13567 14567 23456 23457 23467 23567 24567 34567 

以上がPHP を使用して、7 つの数値 (1、2、3、4、5、6、7) の配列から 5 つの数値の一意の組み合わせをすべて生成するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
トラフィックの高いウェブサイトのPHPパフォーマンスチューニングトラフィックの高いウェブサイトのPHPパフォーマンスチューニングMay 14, 2025 am 12:13 AM

thesecrettokeepingaphp-poweredwebsterunningsmootlyunderheavyloadinvolvesseveralkeystrategies:1)emform opcodecoduceSciptionexecutiontime、2)aatabasequerycachingwithiThing withiThistolessendavasoload、

PHPでの依存関係注射:初心者向けのコード例PHPでの依存関係注射:初心者向けのコード例May 14, 2025 am 12:08 AM

コードをより明確かつ維持しやすくするため、依存関係が関心(DI)に注意する必要があります。 1)DIは、クラスを切り離すことにより、よりモジュール化されます。2)テストとコードの柔軟性の利便性を向上させ、3)DIコンテナを使用して複雑な依存関係を管理しますが、パフォーマンスの影響と円形の依存関係に注意してください。

PHPパフォーマンス:アプリケーションを最適化することは可能ですか?PHPパフォーマンス:アプリケーションを最適化することは可能ですか?May 14, 2025 am 12:04 AM

はい、最適化されたAphPossibleandessention.1)CachingingusapCutoredatedAtabaseload.2)最適化、効率的なQueries、およびConnectionPooling.3)EnhcodeCodewithBultinctions、Avoididingglobalbariables、およびUsingopcodeching

PHPパフォーマンスの最適化:究極のガイドPHPパフォーマンスの最適化:究極のガイドMay 14, 2025 am 12:02 AM

keyStrategIestsoSificlyvoostphpappliceperformanceare:1)useopcodecachinglikeToreexecutiontime、2)最適化abaseの相互作用とプロペラインデックス、3)3)構成

PHP依存性噴射コンテナ:クイックスタートPHP依存性噴射コンテナ:クイックスタートMay 13, 2025 am 12:11 AM

aphpDependencyInjectionContaineriSATOULTAINATINAGECLASSDEPTINCIES、強化測定性、テスト可能性、および維持可能性。

PHPの依存噴射対サービスロケーターPHPの依存噴射対サービスロケーターMay 13, 2025 am 12:10 AM

SELECT DEPENTENCINGINOFCENT(DI)大規模なアプリケーションの場合、ServicElocatorは小さなプロジェクトまたはプロトタイプに適しています。 1)DIは、コンストラクターインジェクションを通じてコードのテスト可能性とモジュール性を改善します。 2)ServiceLocatorは、センター登録を通じてサービスを取得します。これは便利ですが、コードカップリングの増加につながる可能性があります。

PHPパフォーマンス最適化戦略。PHPパフォーマンス最適化戦略。May 13, 2025 am 12:06 AM

phpapplicationscanbeoptimizedforspeedandEfficiencyby:1)enabingopcacheinphp.ini、2)PreparedStatementswithpordatabasequeriesを使用して、3)LoopswithArray_filterandarray_mapfordataprocessing、4)の構成ngincasaSearverseproxy、5)

PHPメールの検証:電子メールが正しく送信されるようにしますPHPメールの検証:電子メールが正しく送信されるようにしますMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

SublimeText3 Linux 新バージョン

SublimeText3 Linux 新バージョン

SublimeText3 Linux 最新バージョン

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

VSCode Windows 64 ビットのダウンロード

VSCode Windows 64 ビットのダウンロード

Microsoft によって発売された無料で強力な IDE エディター

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)