web-dev-qa-db-fra.com

Permutations - tous les ensembles de nombres possibles

J'ai des nombres, de 0 à 8. J'aimerais en résultat, tous les ensembles possibles de ces nombres, chaque ensemble doit utiliser tous les nombres, chaque nombre ne peut apparaître qu'une seule fois dans un ensemble.

Je voudrais voir une solution faite en PHP qui pourrait imprimer le résultat. Ou, au moins, je voudrais un rafraîchissement en théorie de la combinatoire, comme je l'ai oublié depuis longtemps. Quelle est la formule calculer combien de permutations y aura-t-il?

Ensembles d'exemples:

  • 0-1-2-3-4-5-6-7-8
  • 0-1-2-3-4-5-6-8-7
  • 0-1-2-3-4-5-8-6-7
  • 0-1-2-3-4-8-5-6-7
  • 0-1-2-3-8-4-5-6-7
  • 0-1-2-8-3-4-5-6-7
  • etc...
33
Deele

Vous recherchez la formule des permutations:

nPk = n!/(n-k)!

Dans votre cas, vous avez 9 entrées et vous souhaitez toutes les choisir, c'est 9P9 = 9! = 362880

Vous pouvez trouver un algorithme PHP pour permuter dans la recette 4.26 du "PHP Cookbook" d'O'Reilly.

pc_permute(array(0, 1, 2, 3, 4, 5, 7, 8));

Copié depuis O'Reilly:

function pc_permute($items, $perms = array( )) {
    if (empty($items)) { 
        print join(' ', $perms) . "\n";
    }  else {
        for ($i = count($items) - 1; $i >= 0; --$i) {
             $newitems = $items;
             $newperms = $perms;
             list($foo) = array_splice($newitems, $i, 1);
             array_unshift($newperms, $foo);
             pc_permute($newitems, $newperms);
         }
    }
}
49
yzxben

Depuis PHP 5.5 vous pouvez utiliser Generators . Les générateurs économisent beaucoup de mémoire et sont beaucoup plus rapides (plus de la moitié par rapport à pc_permute () ). Donc, si vous avez une chance d'avoir PHP 5.5 installé, vous voulez certainement des générateurs. Cet extrait est porté depuis Python: https://stackoverflow.com/a/104436/3745311

function permutations(array $elements)
{
    if (count($elements) <= 1) {
        yield $elements;
    } else {
        foreach (permutations(array_slice($elements, 1)) as $permutation) {
            foreach (range(0, count($elements) - 1) as $i) {
                yield array_merge(
                    array_slice($permutation, 0, $i),
                    [$elements[0]],
                    array_slice($permutation, $i)
                );
            }
        }
    }
}

Exemple d'utilisation:

$list = ['a', 'b', 'c'];

foreach (permutations($list) as $permutation) {
    echo implode(',', $permutation) . PHP_EOL;
}

Production:

a,b,c
b,a,c
b,c,a
a,c,b 
c,a,b
c,b,a
29
spezifanta

Étant donné que cette question revient souvent dans les résultats de recherche Google, voici une version modifiée de la réponse acceptée qui renvoie toutes les combinaisons dans un tableau et les transmet comme valeur de retour de la fonction.

function pc_permute($items, $perms = array( )) {
    if (empty($items)) {
        $return = array($perms);
    }  else {
        $return = array();
        for ($i = count($items) - 1; $i >= 0; --$i) {
             $newitems = $items;
             $newperms = $perms;
         list($foo) = array_splice($newitems, $i, 1);
             array_unshift($newperms, $foo);
             $return = array_merge($return, pc_permute($newitems, $newperms));
         }
    }
    return $return;
}

Utiliser:

$value = array('1', '2', '3');
print_r(pc_permute($value));
22
dAngelov

J'ai quelque chose que tu aimeras

function combination_number($k,$n){
    $n = intval($n);
    $k = intval($k);
    if ($k > $n){
        return 0;
    } elseif ($n == $k) {
        return 1;
    } else {
        if ($k >= $n - $k){
            $l = $k+1;
            for ($i = $l+1 ; $i <= $n ; $i++)
                $l *= $i;
            $m = 1;
            for ($i = 2 ; $i <= $n-$k ; $i++)
                $m *= $i;
        } else {
            $l = ($n-$k) + 1;
            for ($i = $l+1 ; $i <= $n ; $i++)
                $l *= $i;
            $m = 1;
            for ($i = 2 ; $i <= $k ; $i++)
                $m *= $i;            
        }
    }
    return $l/$m;
}

function array_combination($le, $set){

    $lk = combination_number($le, count($set));
    $ret = array_fill(0, $lk, array_fill(0, $le, '') );

    $temp = array();
    for ($i = 0 ; $i < $le ; $i++)
        $temp[$i] = $i;

    $ret[0] = $temp;

    for ($i = 1 ; $i < $lk ; $i++){
        if ($temp[$le-1] != count($set)-1){
            $temp[$le-1]++;
        } else {
            $od = -1;
            for ($j = $le-2 ; $j >= 0 ; $j--)
                if ($temp[$j]+1 != $temp[$j+1]){
                    $od = $j;
                    break;
                }
            if ($od == -1)
                break;
            $temp[$od]++;
            for ($j = $od+1 ; $j < $le ; $j++)    
                $temp[$j] = $temp[$od]+$j-$od;
        }
        $ret[$i] = $temp;
    }
    for ($i = 0 ; $i < $lk ; $i++)
        for ($j = 0 ; $j < $le ; $j++)
            $ret[$i][$j] = $set[$ret[$i][$j]];   

    return $ret;
}

Voici comment l'utiliser:

Pour obtenir le nombre de combinaisons:

combination_number(3,10); // returns number of combinations of ten-elements set.

Pour obtenir toutes les combinaisons possibles:

$mySet = array("A","B","C","D","E","F");
array_combination(3, $mySet); // returns all possible combinations of 3 elements of six-elements set.

J'espère que vous utilisez cela.

10
Piotr Salaciak

Ceci est ma version de classe. Cette classe crée et renvoie un tableau permuté comme résultat

class Permutation {
    private $result;

    public function getResult() {
        return $this->result;
    }

    public function permute($source, $permutated=array()) {
        if (empty($permutated)){
            $this->result = array();
        }
        if (empty($source)){
            $this->result[] = $permutated;
        } else {
            for($i=0; $i<count($source); $i++){
                $new_permutated = $permutated;
                $new_permutated[] = $source[$i];
                $new_source =    array_merge(array_slice($source,0,$i),array_slice($source,$i+1));
                $this->permute($new_source, $new_permutated);
            }
        }
        return $this;
    }
}

$arr = array(1,2,3,4,5);
$p = new Permutation();
print_r($p->permute($arr)->getResult());

Les trois dernières lignes pour tester ma classe.

5
Jeff_Alieffson

J'ai porté le Python itertools répertorié ici (à l'aide de générateurs). L'avantage par rapport aux solutions publiées jusqu'à présent est qu'il vous permet de spécifier r (taille de permutation) ).

function permutations($pool, $r = null) {
    $n = count($pool);

    if ($r == null) {
        $r = $n;
    }

    if ($r > $n) {
        return;
    }

    $indices = range(0, $n - 1);
    $cycles = range($n, $n - $r + 1, -1); // count down

    yield array_slice($pool, 0, $r);

    if ($n <= 0) {
        return;
    }

    while (true) {
        $exit_early = false;
        for ($i = $r;$i--;$i >= 0) {
            $cycles[$i]-= 1;
            if ($cycles[$i] == 0) {
                // Push whatever is at index $i to the end, move everything back
                if ($i < count($indices)) {
                    $removed = array_splice($indices, $i, 1);
                    array_Push($indices, $removed[0]);
                }
                $cycles[$i] = $n - $i;
            } else {
                $j = $cycles[$i];
                // Swap indices $i & -$j.
                $i_val = $indices[$i];
                $neg_j_val = $indices[count($indices) - $j];
                $indices[$i] = $neg_j_val;
                $indices[count($indices) - $j] = $i_val;
                $result = [];
                $counter = 0;
                foreach ($indices as $indx) {
                    array_Push($result, $pool[$indx]);
                    $counter++;
                    if ($counter == $r) break;
                }
                yield $result;
                $exit_early = true;
                break;
            }
        }
        if (!$exit_early) {
            break; // Outer while loop
        }
    }
}

Cela fonctionne pour moi, mais aucune promesse! Exemple d'utilisation:

$result = iterator_to_array(permutations([1, 2, 3, 4], 3));
foreach ($result as $row) {
    print implode(", ", $row) . "\n";
}
4
eddiewould

Il s'agit d'une simple fonction récursive qui imprime toutes les permutations (écrite en pseudocode)

function rec(n, k) {
    if (k == n) {
        for i = 0 to n-1
            print(perm[i], ' ');
        print('\n');
    }
    else {
        for i = 0 to n-1 {
            if (not used[i]) {
                used[i] = true;
                perm[k] = i;
                rec(n, k+1);
                used[i] = false;
            }
        }
    }
}

Et cela s'appelle comme ceci:

rec(9, 0);
2
fdermishin

Ordre lexicographique. Il n'y a pas de récursivité. Presque aucune limite de longueur de tableau. Il n'y a aucune sorte. Ça tourne plutôt vite. C'est facile à comprendre. Moins: il donne un avis, mais vous pouvez ajouter une condition pour commencer la comparaison avec le deuxième élément ou error_reporting (0).

$a = array(
1,
2,
3,
4,
5
 );
    $b = array_reverse($a);
    print_r($a);
   //here need "br"
  while ($a != $b)
{
foreach(array_reverse($a, true) as $k => $v)
    {
    if ($v < $a[$k + 1])
        {
        foreach(array_reverse($a, true) as $ka => $val)
            {
            if ($val > $v) break;
            }

        $ch = $a[$k];
        $a[$k] = $a[$ka];
        $a[$ka] = $ch;
        $c = array_slice($a, 0, $k + 1);
        print_r($a = array_merge($c, array_reverse(array_slice($a, $k + 1))));
        //here need "br"
        break;
        }
       }
      }
2
dcc0

Voici ma proposition, j'espère un peu plus claire que la réponse acceptée.

   function permutate($elements, $perm = array(), &$permArray = array())
{
    if(empty($elements))
    {
       array_Push($permArray,$perm); return;
    }

    for($i=0;$i<=count($elements)-1;$i++)
    {
       array_Push($perm,$elements[$i]);
       $tmp = $elements; array_splice($tmp,$i,1);
       permutate($tmp,$perm,$permArray);
       array_pop($perm);
    }

    return $permArray;
}

et utilisation:

$p = permutate(array('a','b','c'));
foreach($p as $perm)
    print join(",",$perm)."|\n";
1
Jarek

Essaye ça...

//function to generate and print all N! permutations of $str. (N = strlen($str))

function permute($str,$i,$n) {
   if ($i == $n)
       print "$str\n";
   else {
        for ($j = $i; $j < $n; $j++) {
          swap($str,$i,$j);
          permute($str, $i+1, $n);
          swap($str,$i,$j); // backtrack.
       }
   }
}

// function to swap the char at pos $i and $j of $str.

function swap(&$str,$i,$j) {
    $temp = $str[$i];
    $str[$i] = $str[$j];
    $str[$j] = $temp;
}   
$str = "0123";
permute($str,0,strlen($str)); // call the function.
1
jeswin

Vous parlez essentiellement de permutations où n et k sont 9, vous aurez donc 9! différentes permutations; voir ceci: http://en.wikipedia.org/wiki/Permutation .

1
Argote
//function call
print_r(combinations([1,2,3,4,5,6,7,8,9,10,11,12,13]));
/**
 * @param $mainArray
 * @param int $size - optional
 * @param array $combinations - optional
 * @return mixed
 */
function combinations($mainArray, $size = 3, $combinations = [])
{
    if (empty($combinations)) {
        $combinations = $mainArray;
    }
    if ($size == 1) {
        return str_replace('-','',$combinations);;
    }
    $newCombination = array();
    foreach ($mainArray as $key => $val){
        foreach ($combinations as $char) {
            if(in_array($val, explode('-', $char))){
                continue;
            }
            $newCombination[] = $val . '-' . $char;
        }
    }
    return combinations($mainArray, $size - 1, $newCombination);
}

// ========================= Solution suivante ====================== =============

function sampling($chars, $size, $combinations = array()) {
    # if it's the first iteration, the first set 
    # of combinations is the same as the set of characters
    if (empty($combinations)) {
        $combinations = $chars;
    }
    # we're done if we're at size 1
    if ($size == 1) {
        return $combinations;
    }
    # initialise array to put new values in
    $new_combinations = array();
    # loop through existing combinations and character set to create strings
    foreach ($combinations as $combination) {
        foreach ($chars as $char) {
            $new_combinations[] = $combination .'-'. $char ; 

        }
    }
    # call same function again for the next iteration
    return $this->sampling($chars, $size - 1, $new_combinations);
}
function array_has_dupes($array) {
   return count($array) !== count(array_unique($array));
}   
function total() {
    // Generate ticket price
    $arrfinal = array();
    // combinations
    $chars = array(1,2,3,4,5,6,7,8,9,10,11,12,13); // for 10 digits
    $combinations = $this->sampling($chars, 3);
    //print_r($combinations); //exit;

    foreach($combinations as $key => $val)
    {
        $arr = explode('-', $val);//str_split($val);
        if(!$this->array_has_dupes($arr)){
            $arrfinal[] = str_replace('-', '', $val);
        }
    }
  echo '<pre>'; print_r($arrfinal); echo '</pre>';
}
0
Pravin Kanaujia

Solution simple utilisant la récursivité

function filterElement($element){  
  if(is_array($element[0])){
    return $element[0];
  }
  # base case
  return $element;
}

function permutation($input, $path){  
  // base case 1
  if(count($input) == 0){
    return [$path];
  }

  $output = [];
  foreach($input as $index => $num){     # 1, 2,3, 4
    $copyPath = $path; # copy the path - []
    $copyPath[] = $num;  # append the number [1]

    # remove the current number
    $inputLocal = $input; 
    unset($inputLocal[$index]); # [2, 3, 4]       
    $permute = permutation($inputLocal, $copyPath); # call [2, 3, 4], [1]

    # for all element find add to output
    foreach($permute as $ele){
      # filter ouput
      $output[] = filterElement($ele);    
    }
  }

  return $output;
}


print_r(permutation([1,2,3,4], []));

production

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
        )

    [1] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 4
            [3] => 3
        )

    [2] => Array
        (
            [0] => 1
            [1] => 3
            [2] => 2
            [3] => 4
        )

    [3] => Array
        (
            [0] => 1
            [1] => 3
            [2] => 4
            [3] => 2
        )

    [4] => Array
        (
            [0] => 1
            [1] => 4
            [2] => 2
            [3] => 3
        )

    [5] => Array
        (
            [0] => 1
            [1] => 4
            [2] => 3
            [3] => 2
        )

    [6] => Array
        (
            [0] => 2
            [1] => 1
            [2] => 3
            [3] => 4
        )

    [7] => Array
        (
            [0] => 2
            [1] => 1
            [2] => 4
            [3] => 3
        )

    [8] => Array
        (
            [0] => 2
            [1] => 3
            [2] => 1
            [3] => 4
        )

    [9] => Array
        (
            [0] => 2
            [1] => 3
            [2] => 4
            [3] => 1
        )

    [10] => Array
        (
            [0] => 2
            [1] => 4
            [2] => 1
            [3] => 3
        )

    [11] => Array
        (
            [0] => 2
            [1] => 4
            [2] => 3
            [3] => 1
        )

    [12] => Array
        (
            [0] => 3
            [1] => 1
            [2] => 2
            [3] => 4
        )

    [13] => Array
        (
            [0] => 3
            [1] => 1
            [2] => 4
            [3] => 2
        )

    [14] => Array
        (
            [0] => 3
            [1] => 2
            [2] => 1
            [3] => 4
        )

    [15] => Array
        (
            [0] => 3
            [1] => 2
            [2] => 4
            [3] => 1
        )

    [16] => Array
        (
            [0] => 3
            [1] => 4
            [2] => 1
            [3] => 2
        )

    [17] => Array
        (
            [0] => 3
            [1] => 4
            [2] => 2
            [3] => 1
        )

    [18] => Array
        (
            [0] => 4
            [1] => 1
            [2] => 2
            [3] => 3
        )

    [19] => Array
        (
            [0] => 4
            [1] => 1
            [2] => 3
            [3] => 2
        )

    [20] => Array
        (
            [0] => 4
            [1] => 2
            [2] => 1
            [3] => 3
        )

    [21] => Array
        (
            [0] => 4
            [1] => 2
            [2] => 3
            [3] => 1
        )

    [22] => Array
        (
            [0] => 4
            [1] => 3
            [2] => 1
            [3] => 2
        )

    [23] => Array
        (
            [0] => 4
            [1] => 3
            [2] => 2
            [3] => 1
        )

)
0
Faiz Rasool