Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

203
Vistas
why recursion function returns "NaN" here

I have to find the sum of the absolute difference between consecutive elements of the array. But sumAbsArr function returns nun

var arr = [1, 5, 2];
var n = 3;
var cur = 0;

console.log(sumAbsArr(arr, n, cur))

function sumAbsArr(arr, n, cur) {
  if (n == cur) {
    return 0
  }
  var abs = Math.abs(arr[cur] - arr[cur + 1])
  var ans = abs + sumAbsArr(arr, n, cur + 1)
  return ans
}

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I think you are wrong at placing the condition. Look at arr[cur+1] (at line 11), when cur = 3 the cur+1 is out of range (arr index is start at 0 and end at arr.length-1 which is 2). So to prevent arr[cur+1] have NaN value, you have to change the condition

var arr = [1, 5, 2];
var n = 3;
var cur = 0;

console.log(sumAbsArr(arr, n, cur))

function sumAbsArr(arr, n, cur) {
  // change the condition to stay within the range
  if (cur == n-1) { 
    return 0
  }
  var abs = Math.abs(arr[cur] - arr[cur + 1])
  var ans = abs + sumAbsArr(arr, n, cur+1)
  return ans
}

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda