1

Тема: Комбінаторика

По мотивам http://bit.ly/1kw2uEg
Написав PHP класс, тримайте, можливо комусь знадобиться для якогось веб-сервісу..

class PermutationsWithRepetition {

   private $src, 
           $len,
           $k = 0, 
           $n = 0,
           $out = [], 
           $stack = [];

   function __construct($src, $len) {

      $this->src = $src;
      $this->len = $len - 1;
      $this->count = count($this->src);

   }

    public function next() {

        while (true) {

            while ($this->n < $this->count) {

                $this->out[$this->k] = $this->src[$this->n++];

                if ($this->k == $this->len) return array_slice($this->out, 0);

                else {

                    if ($this->n < $this->count) {

                        $this->stack[] = $this->k;
                        $this->stack[] = $this->n;
                    }

                    $this->k++;
                    $this->n = 0;
                }
            }

            if (!count($this->stack)) break;

            $this->n = array_pop($this->stack);
            $this->k = array_pop($this->stack);
        }

        return false;
    }

    public function rewind() { 

     $this->k = 0;
     $this->n = 0; 
     $this->out = []; 
     $this->stack = []; 

   }

    public function result() {

        $this->rewind();

        $data = [];

        while ($res = $this->next()) { 

         $data[] = $res;

         if (!$data) break;

    }

     return $data;

  }

  function __destruct() { 
  
  }

}

Використання

$base = ['яблуко', 'груша', 'слива', 'абрикос', 'вишня'];
$length = 5;

$perms = new PermutationsWithRepetition($base, $length);
$perms->rewind();
$perms->next();
echo 'Комбінацій: '.count($perms->result()).'<br>';
foreach($perms->result() as $num => $comb)
echo implode(',', $comb).'<br>';
Подякували: 221VOLT1