Code challenges week of Nov. 5

Code solutions – next week I’ll try to start talking through my thought process more, but suffice to say for most if not all of these, there’s a better way to do it. I can tell I like programming because I get mad if I didn’t figure out the “smart” way.

I think it’s important to document the growth process though, so here’s my junior attempts at problem-solving.

 // Check for Palindromes
function palindrome(str) {
 // Good luck!
 str = str.toLowerCase().replace(/[^A-Za-z0-9]/g, "");
 var bStr = str.split("").reverse().join("");
 if(str == bStr) {
 return true;
 } else {return false;}
}

(^ this one is particularly infuriating. I mean, COME ON. It’s also part of the drive to build my algorithm skills more efficiently, so: here’s to that.)

  // Confirm the end of a string

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

confirmEnding("Bastian", "n");

 

//Split an array into a 2d array grouped based on the size of a second argument

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

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

 

//Find if any of the characters in the seccond string are in the first string

function mutation(arr) {
  for (i=0; i < arr[1].length; i++) {
    if(arr[0].toLowerCase().indexOf(arr[1][i].toLowerCase()) < 0)
    return false;
  }  
  return true;
}

mutation(["Mary", "Army"]);

 

// Find if any of the subsequent arguments are in the first argument (an array)

function destroyer(arr) {
  
  var args = Array.from(arguments).slice(1);

    return arguments[0].filter(function(elem) {
      return !args.includes(elem);
    });
}

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

 

//Sort the provided array and find the would-be index of the second argument

function getIndexToIns(arr, num) {
  arr = arr.sort(function(a, b) {return a - b;});
  if (num > arr[arr.length -1]) {
    return arr.length;
  }
  return arr.findIndex(function(elem){
    return elem >= num;
  });
}

getIndexToIns([2, 5, 10], 15);

 

Leave a Reply

Your email address will not be published. Required fields are marked *