How to transform loops into recursive function

2

This program makes the professional aptitude test based on the logic of fuzzy relations. I have to transform these loops into a recursive function, I researched and even understood how a recursive function should be implemented, but I could not figure out a way to use those loops in one. The recursive function invokes itself as a loop of repetition until a stop condition is satisfied. How could I make these loops a recursive function?

$aptidoes = array (
array ("aptidao_id" => "3","cod" => "ap1", "aptidao" => "Nível de Raciocínio Lógico?"),
array ("aptidao_id" => "4","cod" => "ap2", "aptidao" => "Gosta de Cálculos?"),
array ("aptidao_id" => "5","cod" => "ap3", "aptidao" => "Nível de Curiosidade?")
);

$casos = array (
array ("caso_id" => "35","nome" => "KELLY", "ap1" => "0.1", "ap2" => "0.1", "ap3" => "0.1")
);

$profissoes = array (
array ("profissao_id" => "1","profissao" => "Cientista da Computação", "ap1" => "1", "ap2" => "0.9", "ap3" => "0.9"),
array ("profissao_id" => "2","profissao" => "Psicologo", "ap1" => "0.5", "ap2" => "0", "ap3" => "0.6"),
array ("profissao_id" => "3","profissao" => "Professor de Humanas", "ap1" => "0.4", "ap2" => "0", "ap3" => "0.6")
);


//Pega repete a analise somente para o caso corrente, ou seja 1.
for ($p=0; $p < 1; $p++) { 
//Inicializa o arrey.
$_max = array();
//Pega todas as profissoes registradas no banco para análise.
for ($d = 0; $d < count($profissoes); $d++) {
    //Inicializa o arrey.
    $_min = array();
    //Pega todos as aptidões registrados no banco para análise.
    for ($i=1; $i < count($aptidoes)+1; $i++) { 
        //Cria um array com as relações (aptidão x profissao) e (aptidão x casos), e gera o valor mínimo de cada uma.
        array_push($_min, min($profissoes[$d]['ap'.$i],$casos[$p]['ap'.$i]));       
    }
//Recebe o valor mínimo da relação, para cada profissão.
$valor = max($_min);
//Gera um array com o valor máximo, da relação dos mínimos.
array_push($_max, $valor.' - '.$profissoes[$d]['profissao']);

  };
};

//Trás o resultado e a porcentagem de precisão.
echo '<h3><b>'.explode ("-", max($_max))[1].'</b> com precisão de '.(explode ("-", max($_max))[0] * 100).'%</h3>';
    
asked by anonymous 27.10.2017 / 20:44

1 answer

0

First you need to understand the loop structure in PHP . Briefly, you have:

for (a; b; c)
    d;

Where:

  • a : this is an expression that is executed only once before the loop begins;
  • b : This is a condition executed before each loop step. If true the loop continues, otherwise the loop for;
  • c : this is an expression that is executed at the end of each step;
  • d : is an expression that is executed for each step of the loop.

Therefore, the for above is equivalent to this while :

a;
while(b) {
    d;
    c;
}

How to turn this into a recursive algorithm? Recursion is a method to call itself, so you need the following:

function recursiva(parametrosOriginais) {
    if (b) return;
    else {
        d;
        c;
        return recursiva(parametrosAlterados);
    }
}

a;
recursiva(parametros);

Note that in the loop with while and recursão , expressions c and d can be combined into one. But most importantly: in recursion, running within else will change the parameters that will be passed to the next call. In all cases, b is the stop condition. When hit, the algorithm for and you have a result.

Here's a factorial, iterative, and then recursive example in PHP.

Iterative with for :

$param = 4; // pode ser qualquer outro número
$resultado = 1;
for ($i = $param; $i > 0; i--) {
    $resultado *= $i;
}

Iterative with while :

$param = 4; // pode ser qualquer outro número
$resultado = 1;
$i = $param
while ($i > 0) {
    $resultado *= $i;
    $i--;
}

And finally, recursive:

function fatorial($numero) {
    if ($numero == 1) return 1;
    else {
        $proximo = $numero - 1;
        return $numero * fatorial(proximo);
    }
}

$param = 4;
$resultado = fatorial($param);

Try to notice the pattern, and you can turn almost any iterative algorithm into a recursive version (the reverse is not always true). Note that the recursive function can receive more than one parameter if necessary.

This goes for dozens of other languages, from C to Javascript.

    
06.11.2017 / 19:48