Skip to content

Instantly share code, notes, and snippets.

@plembo
Last active May 21, 2018 04:28
Show Gist options
  • Save plembo/7d0b736e0647ee41bc3c2afac7498042 to your computer and use it in GitHub Desktop.
Save plembo/7d0b736e0647ee41bc3c2afac7498042 to your computer and use it in GitHub Desktop.
FCC Basic Algorithms

freeCodeCamp: Basic Algorithms

My lame answers to Basic Algorithms challenges on freeCodeCamp.

Reverse a String

function reverseString(str) {
  
  var a = str.split('');
  a = a.reverse();
  str = a.join('');
  return str;
  
}
reverseString("hello");

Maybe a little too drawn out for some, but it works!

Factorialize a Number

function factorialize(num) {
  if(num < 0) {
    return -1;
  }
  else if (num == 0) {
    return 1;
  }
  else {
    return (num * factorialize(num - 1));
  }
}

factorialize(5);

The first time I found a reason to use recursion outside of a recursion exercise! That wasn't obvious to me at all, although it looks like most people realize right off it's part of the answer.

Check for Palindromes

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

The big stumbling block for me was in failing to add the underscore character to the regex, as it is considered an alphanumeric (and therefore included among the characters that would be matched by "\w"). Of course the test data did include both strings with mixed case, numbers and underscores! My answer, once again, was more verbose than the official solution, but the verbosity helped me grok what was happening.

Find the Longest Word in a String

function findLongestWord(str) {
  var a = str.split(' ');
  var longest = 0;
  
  for (var i = 0; i < a.length; i++){
    if (a[i].length > longest){
      longest = a[i].length;
    }
  }
  return longest;
}

findLongestWord("The quick brown fox jumped over the lazy dog");

Took me a long time to figure this one out, although I knew right from the beginning that I'd want to use a for loop. Read a lot of posts on stackoverflow.com, but most of them were beyond me. My initial solution used more variables to get the same result, but after looking at what others had done I "reduced" that :-)

Title Case a string

function titleCase(str) {
    var w = str.toLowerCase().split(' ');

    for(var i = 0; i < w.length; i++) {
        var l = w[i].split('');
        l[0] = l[0].toUpperCase();
        w[i] = l.join('');
    }
    return w.join(' ');
}

console.log(titleCase("I'm a little tea pot"));

Right off I knew this would require treating the string as an array and then somehow looping through each word before joining them all together again. A lot of the solutions I found seemed cumbersome to me. I found the basis for the above in this post. I especially liked the second version that employed different variables for words and letters, as it made what was happening clearer to me.

Array of largest number in each of 4 subarrays

// Return array of the largest numbers in each of 4 subarrays

function largestOfFour(arr) {
    var ans = [];
    for(var i=0; i < arr.length; i++) {
        var lg = 0;
        for(var s=0; s < arr[i].length; s++) {
            if(arr[i][s] > l) {
                lg = arr[i][s];
            }
        }
        ans.push(lg);
  }
  return ans;
}

var r = largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
console.log(r);

I really had no clue how to tackle this. Fortunately others on the Internet did. The answer by the OP in this post made the most sense to me, in that I could follow its logic. Guess this was the moment when knowing how to address a subarray saves someone's life.

Confirm ending

function confirmEnding(str, target) {
  var n = target.length;
  return str.substr(-n) === target;
}
console.log(confirmEnding("Bastian", "n"));

The task is to check to see if the end of a string matches the string specified as the target. This goes beyond merely matching the last character in a string, which could be done using a simple "substr(str, -1)". In ES6 there is an endsWith() function, but in this challenge they wanted you to use substr or substring.

Repeat a string specified times

function repeatStringNumTimes(str, num) {
  // repeat after me
  for(var i = num; i > 0; i--) {
    console.log(str);
  }
}
repeatStringNumTimes("abc", 3);
@plembo
Copy link
Author

plembo commented May 3, 2018

I like how freeCodeCamp will accept solutions that might not be the most elegant, as long as the work. But that makes it even more important to study the official answers and their alternatives. Most of us learn to read by.... reading. The same holds true for learning to code, I think.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment