Tip on how to turn loops into recursive function

Asked

Viewed 641 times

2

This program takes the professional aptitude test based on the logic of Fuzzy relations. I have to turn these loops into a recursive function, researched and even understood how a recursive function should be implemented, but I couldn’t envision a way to use these loops in one. The recursive function invokes itself as a repeat loop until a stop condition is satisfied. How could I turn these loops into 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>';
  • 3

    teste de aptidão profissional baseado na logica fuzzy http://i0.kym-cdn.com/photos/images/facebook/000/852/286/9ac.jpg

  • I must not be getting it right. Help me. Pfv

1 answer

0

First you need to understand the structure of the PHP loop. In short, you have:

for (a; b; c)
    d;

Where:

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

Therefore, the for above is equivalent to this while:

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

How to turn this into a recursive algorithm? Recursion consists of a method calling itself, so you need the following:

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

a;
recursiva(parametros);

Note that both in the loop with while how much in the recursão, the expressions c and d can be combined into one. But most importantly: in recursion, the execution within the else will modify the parameters that will be passed to the next call. In all cases, b is the stop condition. When it is reached, the algorithm stops and you have a result.

Follows an example of factorial, iterative and then recursive, 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 understand 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 needed.

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

  • Renan. Thank you very much. It helped me a lot this your explanation.

Browser other questions tagged

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