"Si un trabajador quiere hacer bien su trabajo, primero debe afilar sus herramientas." - Confucio, "Las Analectas de Confucio. Lu Linggong"
Página delantera > Programación > ¿Cómo puedo generar todas las combinaciones únicas de 5 números de una matriz de 7 números (1, 2, 3, 4, 5, 6, 7) usando PHP?

¿Cómo puedo generar todas las combinaciones únicas de 5 números de una matriz de 7 números (1, 2, 3, 4, 5, 6, 7) usando PHP?

Publicado el 2025-03-25
Navegar:469

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 Combinations

se le da una matriz de 7 números (1,2,3,4,5,6,7). El objetivo es encontrar todas las combinaciones posibles de 5 números de esa matriz. Cada combinación debe ser única, lo que significa que no se permiten duplicados. Por ejemplo, (1,2,3,4,5) y (5,4,3,2,1) se consideran la misma combinación.

solución

Una solución posible implica usar la clase de combinaciones, que implementa la interfaz Iterator y proporciona una forma de iterar sobre todas las combinaciones posibles de los números dados. Así es como funciona:

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, ' ';

This code produces the following output:

12345 12346 12347 12356 12357 12367 12456 12457 12467 12567 13456 13457 13467 13567 14567 23456 23457 23467 23567 24567 34567 
Último tutorial Más>

Descargo de responsabilidad: Todos los recursos proporcionados provienen en parte de Internet. Si existe alguna infracción de sus derechos de autor u otros derechos e intereses, explique los motivos detallados y proporcione pruebas de los derechos de autor o derechos e intereses y luego envíelos al correo electrónico: [email protected]. Lo manejaremos por usted lo antes posible.

Copyright© 2022 湘ICP备2022001581号-3