Basic Algorithms Scripting- Guide

I feel as if I am just chopping together the algorithms. I feel like I am using a band-aid fix to solve the Algorithms. How do I shed this feeling? I am sure there are other campers who feels this way. I really feel like I just chopped together a few steps. Here is the algorithm that I am not so proud about.

function findLongestWord(str) {
  var strSplit = str.split(" ");
  var arr = [];
  strSplit.forEach(function(a, b, i){
   arr.push(a.length);
  });
  arr.sort(function(x, y){
    return x - y;
  });
 var num = arr.reverse();
  return num[0];
}
findLongestWord("The quick brown fox jumped over the lazy dog");

Funny, I am feeling the same way after finishing the ‘Check for palindromes’ task. While my solution worked, after I finished a looked at the hint to find a super slick solution compared to mine. It was a bit down-heartening. However, based on what we have learned up to this point, I don’t see how we would come to that solution, so I have the feeling that more advanced techniques will be revealed later in the course.

Here’s my long-winded clunky solution (that works perfectly well!):

  function palindrome(str) {
    // make string lowercase
    str = str.toLowerCase();
      
    //remove all non-alphanumeric chars with regex.
    str = str.replace(/[^0-9a-z]/gi, '');

    // use 2 arrays to compare str and str reversed.
    forArray = [];
    revArray = [];
      
    // create array from str.
    forArray = str.split('');
      
    //create reversed array from first array. .map needed.
    revArray = forArray.map(function(x) {
      return x;
    });
      
    revArray = revArray.reverse();  
    
    //compare the two arrays. Must be equal for a palindrome.
    var i = forArray.length;
    while (i--) {
      if (forArray[i] !== revArray[i]) {
        return false;
      }
    }
    // if the array compare does not fail, then str is a palindrome.
    return true;     
  }

  palindrome("A man, a plan, a canal. Panama");

Here’s the Hint basic solution:

  function palindrome(str) {
  return str.replace(/[\W_]/g, '').toLowerCase() ===str.replace(/[\W_]/g, '').toLowerCase().split('').reverse().join('');
}
1 Like