Number combination

Asked

Viewed 204 times

0

I am trying unsuccessfully to modify this script. I wish he’d make combinations this way.:

12345
12678 ...

and not like he does now:

12345
12346
12347
12348 ...

Follows the code:

<?php
class Combinations implements Iterator
{
    protected $c = null;
    protected $s = null;
    protected $n = 0;
    protected $k = 0;
    protected $pos = 0;

    function __construct($s, $k) {
        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();
    }
    function key() {
        return $this->pos;
    }
    function current() {
        $r = array();
        for($i = 0; $i < $this->k; $i++)
            $r[] = $this->s[$this->c[$i]];
        return is_array($this->s) ? $r : implode('', $r);
    }
    function next() {
        if($this->_next())
            $this->pos++;
        else
            $this->pos = -1;
    }
    function rewind() {
        $this->c = range(0, $this->k);
        $this->pos = 0;
    }
    function valid() {
        return $this->pos >= 0;
    }

    protected function _next() {
        $i = $this->k - 1;
        while ($i >= 0 && $this->c[$i] == $this->n - $this->k + $i)
            $i--;
        if($i < 0)
            return false;
        $this->c[$i]++;
        while($i++ < $this->k - 1)
            $this->c[$i] = $this->c[$i - 1] + 1;
        return true;
    }
}


foreach(new Combinations("1234567", 5) as $substring)
    echo $substring, ' ';

?>
  • a random combination instead of sequential?

  • the sequence of numbers desired is not sufficient to make a logic. What would be the third number of the sequence?

  • The numbers are always a sequence, which can be 10, 20, 30... They would be combined 5 by 5.

  • The goal is to make all numbers be combined, from 3 to 3, with as little repetition as possible, but distributed from 5 to 5. 1, 2 and 3. This unnecessarily increases the combinations, 3 by 3, as desired. 1 2 3 4 5 - 1 2 3 4 6 - 1 2 3 5 6 - 1 2 4 5 6 - 1 3 4 5 6 - 2 3 4 5 6 - . The initial basis is 1.2. Or 12 345... and not 123 45, as above. 1,2,3,4,5 - 1,2,6,7,8 - 1,3,6,7,8 - 2,3,4,5,6 -

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.