mbrien12 / learning-2017

Place for all my tutorial and practice work, with learning resources, plan and backlog
1 stars 1 forks source link

FCC - Algorithm Challenges (50 hours) #30

Closed mbrien12 closed 7 years ago

mbrien12 commented 7 years ago

Write up notes and learnings as I go...

mbrien12 commented 7 years ago

Reverse a string

Approx 5-10 mins

Solution

Reversing a String using split()

var str = 'asdfghjkl';
var strReverse = str.split('').reverse().join(''); // 'lkjhgfdsa'

// split() returns an array on which reverse() and join() can be applied

From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

mbrien12 commented 7 years ago

Factorialize a number

20 mins

Solution

Used a FOR loop


  if (num === 0 || num === 1)
    return 1;
  for (var i = num - 1; i >= 1; i--) {
    num *= i;
  }
  return num;
}
factorialize(5);```

Lots of help from this article https://medium.freecodecamp.com/how-to-factorialize-a-number-in-javascript-9263c89a4b38
mbrien12 commented 7 years ago

Check for Palindromes

30 mins

Solution

Used reg expression to ignore weird symbols, lowercase function and previous function to reverse string then checked them against each other

var clean = /[\W_]/g; 
var lowerCase = str.toLowerCase().replace(clean,'');
var reverse = lowerCase.split('').reverse().join('');
return reverse === lowerCase;

}

palindrome("_eye");

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

https://medium.freecodecamp.com/two-ways-to-check-for-palindromes-in-javascript-64fea8191fd7

mbrien12 commented 7 years ago

Find the longest word in a string

40 mins

Solution

Split sentence into array of words, then used for loop to iterate over and calculate the length. Then compared to LongestWord value and if more then replaced. Started at 0 so when called longest word it was the biggest one

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

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

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length

http://stackoverflow.com/questions/6521245/finding-longest-string-in-array

https://medium.freecodecamp.com/three-ways-to-find-the-longest-word-in-a-string-in-javascript-a2fb04c9757c

mbrien12 commented 7 years ago

Title case a sentence

20 mins

Solution

Split sentence into array of words, then letters and make first letter capitalised then put back together as word and sentence using .join

function titleCase(str) {
  str = str.toLowerCase().split(' ');                // will split the string delimited by space into an array of words

     for(var i = 0; i < str.length; i++){               // str.length holds the number of occurrences of the array...
          str[i] = str[i].split('');                    // splits the array occurrence into an array of letters
          str[i][0] = str[i][0].toUpperCase();          // converts the first occurrence of the array to uppercase
          str[i] = str[i].join('');                     // converts the array of letters back into a word.
     }
     return str.join(' ');                              //  converts the array of words back to a sentence.
}
titleCase("I'm a little tea pot");

https://www.sitepoint.com/community/t/capitalizing-first-letter-of-each-word-in-string/209644/2

mbrien12 commented 7 years ago

Return largest number in arrays

30 mins

Solution

function largestOfFour(arr) {
  var largestNumber = [0,0,0,0];
  for (var arrayIndex = 0; arrayIndex < arr.length; arrayIndex++) {
    for (var subArrayIndex = 0; subArrayIndex < arr[arrayIndex].length; subArrayIndex++) {
      if (arr[arrayIndex][subArrayIndex] > largestNumber[arrayIndex]) {
        largestNumber[arrayIndex] = arr[arrayIndex][subArrayIndex];
      }

    }

  }
  return largestNumber;
}

https://medium.freecodecamp.com/three-ways-to-return-largest-numbers-in-arrays-in-javascript-5d977baa80a1

Things to remember

mbrien12 commented 7 years ago

Confirm the ending

20 mins

Solution

function confirmEnding(str, target) {
  if (str.substr(-target.length) === target) {
    return true;
  } else {
    return false;
  }
  }

confirmEnding("Bastian", "n");

If the target.length is negative, the substr() method will start the counting from the end of the string, which is what you want in this code challenge. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr

https://medium.freecodecamp.com/two-ways-to-confirm-the-ending-of-a-string-in-javascript-62b4677034ac

Wrong attempt


function confirmEnding(str, target) {
  var stringLength = str.length;
  var index = stringLength - 1;
  var ending = str.substr - index;
  if (target === ending) {
    return true;
  }
}

confirmEnding("Bastian", "n");
mbrien12 commented 7 years ago

Repeat a string repeat a string

15 mins

Solution

function repeatStringNumTimes(str, num) {
if (num < 0) {
  return "";
} return str.repeat(num);

}

repeatStringNumTimes("abc", 3);

https://www.w3schools.com/jsref/jsref_repeat.asp

mbrien12 commented 7 years ago

Truncate a string

30 mins

Solution

function truncateString(str, num) {
  if (str.length > num && num > 3) {
    return str.slice(0, (num - 3)) + '...';
  } else if (str.length > num && num <= 3) {
    return str.slice(0, num) + '...';
  } else {
    return str;
  }

}

https://forum.freecodecamp.com/t/freecodecamp-algorithm-challenge-guide-truncate-a-string/16089

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice

Wrong attempt ❌ - didn't work as not including the dots in the count

function truncateString(str, num) {
  var truncate = "";
  var dots = "...";
  if (str.length > num) {
    return truncate.concat(dots);
  } else {
  return str;
  }
}

2nd wrong attempt

function truncateString(str, num) {
  var dots = "...";
  var shortStr = str.length - num;
  var fullLength = str.concat(dots);
  if (fullLength.length > num) {
    return shortStr.concat(dots);
  } else {
  return str;
  }
}
mbrien12 commented 7 years ago

Chunky Monkey

30 mins

Solution

function chunkArrayInGroups(arr, size) {
  var sliced = [];
  for (var i = 0; i < arr.length; i+=size) {
    sliced.push(arr.slice(i, i+size));
  }
  return sliced;
}

chunkArrayInGroups(["a", "b", "c", "d"], 2);

https://forum.freecodecamp.com/t/freecodecamp-algorithm-challenge-guide-chunky-monkey/16005

mbrien12 commented 7 years ago

Slasher Flicks

20 mins

Solution


function slasher(arr, howMany) {
 return arr.splice(howMany);

}

slasher([1, 2, 3], 2);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

mbrien12 commented 7 years ago

Mutations

45 mins

Solution

  1. Convert all to lowercase so easier to compare - grab each element in array by selecting [1]
  2. Convert strings into array of letters
  3. Set up loop and use indexOf to check if letter of second word is in first
function mutation(arr) {
  var letterTest = arr[1].toLowerCase();
  var match = arr[0].toLowerCase();
  for (i=0;i<letterTest.length;i++) {
    if (match.indexOf(letterTest[i]) < 0)
      return false;
  }
  return true;
 }

mutation(["hello", "hey"]);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf

https://medium.com/@marc.bastian.moeller/javascript-comparing-string-letters-freecodecamp-bonfire-mutations-solution-b3e3ca139471

https://github.com/freeCodeCamp/freeCodeCamp/wiki/Algorithm-Mutations

Wrong attempt ❌ says arr.split not a function...?


function mutation(arr) {
  var sliced = arr.slice(0);
  var splitArr = arr.split('');
  var splitSliced = sliced.split('');

    for (var i = 0; i < splitArr.length; i++) {
      for (var e = 0; i < splitSliced.length; i++) {
        if (splitArr[i] == splitSliced[e] ) {
          return true;
        } else {
          return false;

        }
      }
    }
}

mutation(["hello", "hey"]);
mbrien12 commented 7 years ago

Falsy Bouncer ✅ 40 mins

Solution

function bouncer(arr) {
  arr = arr.filter(Boolean);
  return arr;
}

bouncer([7, "ate", "", false, 9]);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean

http://stackoverflow.com/questions/281264/remove-empty-elements-from-an-array-in-javascript

mbrien12 commented 7 years ago

Seek and Destroy

30 mins

Solution

index of -1 means that it's not present

function destroyer(arr) {
  var args = Array.prototype.slice.call(arguments);
  args.splice(0,1);
  return arr.filter(function(element) {
    return args.indexOf(element) === -1;
  });

}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

https://github.com/freeCodeCamp/freeCodeCamp/wiki/Algorithm-Seek-And-Destroy

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

Wrong attempt ❌ 'Zero is not a function'


function destroyer(arr) {
  for (var i = 0; i < arguments.length; i ++) {
    arr = arr.filter(i);
  }
  return arr;
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);
mbrien12 commented 7 years ago

Where do I belong

30 mins

Solution


function getIndexToIns(arr, num) {
  arr.sort(function(a,b) {
    return a-b;
  });

  for (var a = 0; a < arr.length; a++)  {
    if (arr[a] >= num)
      return parseInt(a);
  }

  return arr.length;
}

getIndexToIns([40, 60], 50);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

https://github.com/freeCodeCamp/freeCodeCamp/wiki/Algorithm-Where-Do-I-Belong

mbrien12 commented 7 years ago

Caesars Cipher

20 mins

Solution

function rot13(str) { // LBH QVQ VG!
var newString = [];

  for (var i = 0; i < str.length; i++) {
    if (str.charCodeAt(i) < 65 || str.charCodeAt(i) > 90) {
      newString.push(str.charAt(i));
    } else if (str.charCodeAt(i) > 77) {
      newString.push(String.fromCharCode(str.charCodeAt(i) - 13));
    } else {
      newString.push(String.fromCharCode(str.charCodeAt(i) + 13));
    }
  }
  return newString.join("");
}

// Change the inputs below to test
rot13("SERR PBQR PNZC");

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode

http://www.seth-dehaan.com/2016/01/21/freecodecamp-caesar-s-cipher/