Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

210
Visualizações
Recursive method does not terminate execution on return

good day. I've a problem with a method recursive, this method will print a numbers in the window. the function given a number n, print following a pattern for example:

n= 16, difference = 5

16 11 6 1 -4 1 6 11 16

n= 10, difference = 5

10 5 0 5 10

The code:

function pattern(number, dif, m = 0, nI = 0) {
  if (m === 2) {
    return 0;
  }
  var nI = nI !== 0 ? nI : number;
  if (!(m === 2)) {
    document.write(number + ' ')
  }

  if (number === 0 || number < 0) {
    pattern(number + dif, dif, 1, nI)
  }
  if (m === 0) {
    pattern(number - dif, dif, 0, nI)
  }
  if (m === 1) {
    if (nI == number) {
      pattern(false, false, 2, false)
    }
    pattern(number + dif, dif, 1, nI)
  }
}

pattern(10, 5)

Basiclly when the number is in 'n' again call the function with parameter m = 2, is executed the reurn but it enters in the sum:

if (m===1) {
  if (nI == number) {
    pattern(false, false, 2,false)
  }
  >>> pattern(number+dif, dif, 1,nI) <<<<
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Your code can be simplified a bit. Whenever you call a function foo(), the function body runs, and once the function returns/completes, the code continues its execution from the line after the foo() function call. With this in mind, you recursive function can be simplified by calling pattern() recursively while your number is positive, and then returning (completing the recursive function) to pass the code execution back to the code after the original pattern() call:

function pattern(number,dif) {
  if(number <= 0) {
    document.write(number);
  } else {
    // If number > 0
    document.write(number + ' ');
    pattern(number-dif, dif);
    document.write(' ' + number);
  }
}

pattern(16, 5);

The idea is as follows: When you encounter a positive non-zero number you print it, and then call pattern again, which then prints the number it was given which then calls pattern again etc. until finally, you reach a negative/zero number. When that happens you no longer have any more recursive calls to make (see the if-block above), and so we return to the original caller of our pattern function, which was the previous recursive call. After we have passed control back to the calling funnction, we can again can print the current number:

pattern() --> 16
|  pattern() --> 11
|  |  pattern() --> 6
|  |  |  pattern() --> 1
|  |  |  |  pattern() --> -4 (returns to above function, printing 1 again)
|  |  |  pattern() --> 1
|  |  pattern() --> 6
|  pattern() --> 11
pattern() --> 16

Creating a utility function to accumulate the values into an array and then joining and logging them (rather than having the function perform the logging) is cleaner in my opinion:

function pattern(number, dif) {
  return number <= 0 
    ? [number]
    : [number, ...pattern(number-dif, dif), number];
}

const patternArr = pattern(16, 5);
document.body.textContent = patternArr.join(' ');

about 4 years ago · Juan Pablo Isaza Relatório

0

All your recursive calls of pattern need to be used with return. Otherwise it will keep on going deeper.

function pattern(number,dif,m=0, nI=0) {
    if (m===2) {
        return 0;
    }
    var nI = nI !== 0 ? nI : number;
    if (!(m===2)) {
        document.write(number+' ')
    }

    if (number=== 0 || number < 0){
        return pattern(number+dif, dif, 1,nI)
    }
    if (m===0) {
        return pattern(number-dif, dif, 0,nI)
    }
    if (m===1) {
        if (nI == number) {
            return pattern(false, false, 2,false)
        }
        return pattern(number+dif, dif, 1,nI)
    }
}

pattern(10,5)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda