Home > Mobile >  Recursion issue with my approach or concept or the issue?
Recursion issue with my approach or concept or the issue?

Time:09-16

So I am doing an algorithm challenge where I am given an array of words and I must capitalize the first letter of the word and return the arr with the new words. it must be done with recursion. I believe my approach is wrong, but if it's conceptually please let me know and how I should be thinking about this. If anyone could help describe how I should be approaching this both conceptually and in code it would be really helpful.

To describe my idea of how this is working conceptually:

 1st call: ['Car']   capitalizeFirst([taco, banana]);
 2nd call: ['Taco']   capitalizeFirst([banana]);
 3rd call: ['Banana']   capitalizeFirst(['']);

so then as it walks back it returns

['Banana']   ['""']
['Taco']   ['Banana']
['Car']   ['Taco','Banana']
returns ['Car','Taco','Banana']

but what I Am getting is 'CarTacoBanana'.
here is the approach I took.

function capitalizeFirst (arr) {

  if (!arr.length) return '';
  arr[0] = arr[0].charAt(0).toUpperCase()   arr[0].slice(1);
  return [ arr[0]   capitalizeFirst(arr.slice(1)) ];

}

capitalizeFirst(['car','taco','banana']); // ['Car','Taco','Banana']

(edit) I was able to solve my approach was wrong! here was my solution

  let newArr = [];
  if (!arr.length) {
    return newArr;
  }
  else {
       arr[0] = arr[0].charAt(0).toUpperCase()   arr[0].slice(1);
       newArr.push(arr[0]);
    }
  

  console.log(newArr, 'test');

  return newArr.concat(capitalizeFirst(arr.slice(1)))
  // return newArr;

CodePudding user response:

function capitalizeFirst(arr) {
  // define the recursion terminal condition
  if (!arr.length) return [];
  // utility to capitalize first letter
  const capWord = s => s.charAt(0).toUpperCase()   s.slice(1);
  
 
  // a well-written recursive function makes clear what each iteration does, here:
  // capitalize the first word, then recurse on the remaining words...
  const first = arr[0], rest = arr.slice(1);
  return [ capWord(first), ...capitalizeFirst(rest) ];
}

let arr = [ 'every', 'good', 'boy', 'does', 'fine' ];
let result = capitalizeFirst(arr);
console.log(result);

I think you got the rough idea but you missed some stuff from general algorithm design as well the implementation perspective. It's better to uniformly return something (like [] here) and then combine them to form the answer. So I changed the base case and inductive case a bit and then you can get the properly formatted answer.

This is the rough code and you can check for the basic corner case test on your own from this point onwards.

CodePudding user response:

Your thought process is close but I would suggest changing [""] to a simple [] – I don't see where the empty string is coming in, but it's not needed -

const capitalize = ([ first, ...more ]) =>
  first.toUpperCase()   more.join("")

const capitalizeAll = ([ first, ...more ]) =>
  first == null
    ? []
    : [capitalize(first), ...capitalizeAll(more)]

console.log(capitalizeAll(["car", "taco", "banana"]))

// ["Car", "Taco", "Banana"]

Note, capitalizeAll is nothing more than Array.prototype.map with a hard-coded call to capitalize -

const capitalize = ([ first, ...more ]) =>
  first.toUpperCase()   more.join("")

console.log(["car", "taco", "banana"].map(capitalize))

// ["Car", "Taco", "Banana"]

  • Related