Ir para conteúdo
Fórum Script Brasil

Fabiano Araujo

Membros
  • Total de itens

    1
  • Registro em

  • Última visita

Posts postados por Fabiano Araujo

  1. Amigos, estou tentando, sem sucesso, separar os elementos da string de retorno desse script. 

    O script combina números (linha 57), mas o faz corretamente apenas até 9, porque ele trabalha com caracteres.

    Assim, do 10 em diante não funciona por motivo óbvio: ele considera, por exemplo, que o 10 são dois elementos distintos: 1 e 0.

    Alguém pode ajudar a fazer com que eu escreva de modo separado cada número para que ele entenda que quero ir além do 9?

    <?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('123456789', 3) as $substring){
    
       // echo($substring).'<br>';
    	echo $substring[0]."  ".$substring[1]."  ".$substring[2]."<br />";
    
    }
    
    /* Result:
    1 2 3
    1 2 4
    1 2 5
    1 2 6
    1 2 7
    1 2 8
    1 2 9
    1 3 4
    1 3 5
    1 3 6
    1 3 7
    1 3 8
    1 3 9
    .
    .
    . */
    
    ?>

     

×
×
  • Criar Novo...