Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save akirap3/b10aaa5b7b5cc28655db4223891e88b3 to your computer and use it in GitHub Desktop.
Save akirap3/b10aaa5b7b5cc28655db4223891e88b3 to your computer and use it in GitHub Desktop.

Introduction to Basic Algorithm Scripting

  • To make solving problems easier, it can be helpful to break them down into many chunks. Then, each chunk can be solved one by one.
  • For example, if you are building a calculator, don't try to solve the problem as a whole. First, consider how to get inputs. Then, determine each arithmetic operation one by one. Finally, display the results.

Basic Algorithm Scripting: Convert Celsius to Fahrenheit

function convertToF(celsius) {
  let fahrenheit;
  fahrenheit = celsius * 9/5 + 32;
  return fahrenheit;
}

console.log(convertToF(30));

Basic Algorithm Scripting: Reverse a String

  • Reverse the provided string.

  • You may need to turn the string into an array before you can reverse it.

  • Your result must be a string.

My solution

function reverseString(str) {
  let temp ="";
  for (let i=0;i<str.length; i++){
    temp = str[i]+ temp;
  }
  str = temp;
  return str;
}

console.log(reverseString("hello"));

Solution 1

function reverseString(str) {
  for (var reversedStr = "", i = str.length - 1; i >= 0; i--) {
    reversedStr += str[i];
  }
  return reversedStr;
}

Solution 1, Code Explanation

  • Starting at the last character of the string passed to the function, you build a new string reversedStr from str.

  • During each iteration of the for loop, reversedStr gets concatenated with itself and the current character.

  • Finally, you return the final value of reversedStr.

Solution 2:

function reverseString(str) {
  return str
    .split("")
    .reverse()
    .join("");
}

Solution 2 , Code Explanation

  • Our goal is to take the input, str, and return it in reverse. Our first step is to split the string by characters using split(''). Notice that we don’t leave anything in between the single quotes, this tells the function to split the string by each character.

  • Using the split() function will turn our string into an array of characters, keep that in mind as we move forward.

  • Next we chain the reverse() function, which takes our array of characters and reverses them.

  • Finally, we chain join('') to put our characters back together into a string. Notice once again that we left no spaces in the argument for join, this makes sure that the array of characters is joined back together by each character.

Basic Algorithm Scripting: Factorialize a Number

  • Return the factorial of the provided integer.

  • If the integer is represented with the letter n, a factorial is the product of all positive integers less than or equal to n.

  • Factorials are often represented with the shorthand notation n!

  • For example: 5! = 1 * 2 * 3 * 4 * 5 = 120

  • Only integers greater than or equal to zero will be supplied to the function.

My solution

function factorialize(num) {
  if (num > 0) {
    let sum =1;
    for (let i = 1; i <= num; i++) {
      sum = sum * i;
    }
    num = sum;
    return num;
  } else {
    return 1;
  }
}
factorialize(5);

Solution 1:

function factorialize(num) {
  for (var product = 1; num > 0; num--) {
    product *= num;
  }
  return product;
}

factorialize(5);

Solution 1, Code Explanation

  • Since the return values for the function will always be greater than or equal to 1, product is initialized at one. For the case where the number is 0, the for loop condition will be false, but since product is initialized as 1, it will have the correct value when the return statement is executed.

  • For all numbers passed to the function which are greater than one, the simple for loop will decrement num by one each iteration and recalculate product down to the value 1.

Solution 2:

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

factorialize(5);

Solution 2, Code Explanation

  • Notice at the first line we have the terminal condition, i.e a condition to check the end of the recursion. If num == 0, then we return 1, i.e. effectively ending the recursion and informing the stack to propagate this value to the upper levels.
  • If we do not have this condition, the recursion would go on until the stack space gets consumed, thereby resulting in a Stack Overflow

Solution 3:

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

factorialize(5);

Solution 3, Code Explanation

  • In this solution, we use Tail Recursion to optimize the the memory use.

  • In traditional head recursion, the typical model is that you perform your recursive calls first, and then you take the return value of the recursive call and calculate the result. In this manner, you don’t get the result of your calculation until you have returned from every recursive call.

  • In tail recursion, you perform your calculations first, and then you execute the recursive call, passing the results of your current step to the next recursive step. This results in the last statement being in the form of (return (recursive-function params)).

  • In this solution, with each evaluation of the recursive call, the factorial is updated. This is different from the head-recursive solution where all evaluation calculations are stored on the stack until the base case is reached.

Solution 4:

function factorialize(num, factorial = 1) {
  return num < 0 ? 1 : (
    new Array(num)
      .fill(undefined)
      .reduce((product, val, index) => product * (index + 1), 1)
  );
}
factorialize(5);

Solution 4, Code Explanation

  • In this solution, we used “reduce” function to find the factorial value of the number.
  • We have created an array which has length num. And we filled all elements of the array as undefined. In this case, we have to do this because empty arrays couldn’t reducible. You can fill the array as your wish by the way. This depends on your engineering sight completely.
  • In reduce function’s accumulator is calling product this is also our final value. We are multiplying our index value with the product to find factorial value.
  • We’re setting product’s initial value to 1 because if it was zero products gets zero always.
  • Also the factorial value can’t calculate for negative numbers, first of all, we’re testing this.

Basic Algorithm Scripting: Find the Longest Word in a String

  • Return the length of the longest word in the provided sentence. Your response should be a number.

Solution 1:

function findLongestWordLength(str) {
  var words = str.split(' ');
  var maxLength = 0;

  for (var i = 0; i < words.length; i++) {
    if (words[i].length > maxLength) {
      maxLength = words[i].length;
    }
  }
  return maxLength;
}

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

Solution 1, Code Explanation

  • Take the string and convert it into an array of words. Declare a variable to keep track of the maximum length and loop from 0 to the length of the array of words.

  • Then check for the longest word by comparing the current word to the previous one and storing the new longest word. At the end of the loop just return the number value of the variable maxLength.

Solution 2:

function findLongestWordLength(s) {
  return s.split(' ')
    .reduce(function(x, y) {
      return Math.max(x, y.length)
    }, 0);
}

Solution 2, Code Explanation

  • For more information on reduce click here.
  • In case you’re wondering about that 0 after the callback function, it is used to give an initial value to the x, so that Math.max will know where to start.

Solution 3:

function findLongestWordLength(str) {
  return Math.max(...str.split(" ").map(word => word.length));
}

Solution 3, Code Explanation

  • We provide Math.max with the length of each word as argument, and it will simply return the highest of all.

  • Let’s analyze everything inside the Math.max parenthesees to understand how we do that.

  • str.split(" ") splits the string into an array, taking spaces as separators. It returns this array: [“The”,"quick,“brown”,“fox”,“jumped”,“over”,“the”,“lazy”,“dog”].

  • Then, we will make another array, made from the lengths of each element of the str.split(" ") array with map().

  • str.split(" ").map(word => word.length) returns [3, 5, 5, 3, 6, 4, 3, 4, 3]

  • Finally, we pass the array as argument for the Math.max function with the spread operator ...

  • For more information on map click here.

Solution 4:

function findLongestWordLength(str) {
  //split the string into individual words
  //(important!!, you'll see why later)
  str = str.split(" ");

  //str only has 1 element left that is the longest element,
  //return the length of that element
  if (str.length == 1) {
    return str[0].length;
  }

  //if the first element's length is greater than the second element's (or equal)
  //remove the second element and recursively call the function)
  if (str[0].length >= str[1].length) {
    str.splice(1, 1);
    return findLongestWordLength(str.join(" "));
  }

  //if the second element's length is greater thant the first element's start
  //call the function past the first element
  if (str[0].length <= str[1].length) {
    // from the first element to the last element inclusive.
    return findLongestWordLength(str.slice(1, str.length).join(" "));
  }
}

Basic Algorithm Scripting: Return Largest Numbers in Arrays

  • Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays.
  • Remember, you can iterate through an array with a simple for loop, and access each member with array syntax arr[i].
  • largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]) should return [27, 5, 39, 1001].

Solution 1:

function largestOfFour(arr) {
  var results = [];
  for (var n = 0; n < arr.length; n++) {
    var largestNumber = arr[n][0];
    for (var sb = 1; sb < arr[n].length; sb++) {
      if (arr[n][sb] > largestNumber) {
        largestNumber = arr[n][sb];
      }
    }

    results[n] = largestNumber;
  }

  return results;
}

Solution 1, Code Explanation

  • Create a variable to store the results as an array.
  • Create an outer loop to iterate through the outer array.
  • Create a second variable to hold the largest number and initialise it with the first number. This must be outside an inner loop so it won’t be reassigned until we find a larger number.
  • Create said inner loop to work with the sub-arrays.
  • Check if the element of the sub array is larger than the currently stored largest number. If so, then update the number in the variable.
  • After the inner loop, save the largest number in the corresponding position inside of the results array.
  • And finally return said array.

Solution 2:

function largestOfFour(arr) {
  return arr.map(function(group) {
    return group.reduce(function(prev, current) {
      return current > prev ? current : prev;
    });
  });
}

Solution 2, Code Explanation

  • we map all items within the main array to a new array using Array.prototype.map() and return this array as the final result
  • within each inner array, we reduce its contents down to a single value using Array.prototype.reduce()
  • the callback function passed to the reduce method takes the previous value and the current value and compares the two values
  • if the current value is higher than the previous value we set it as the new previous value for comparison with the next item within the array or returns it to the map method callback if it’s the last item

Solution 3:

function largestOfFour(arr) {
  return arr.map(Function.apply.bind(Math.max, null));
}

Solution 3, Code Explanation

  • TL;DR: We build a special callback function (using the Function.bind method), that works just like Math.max but also has Function.prototype.apply's ability to take arrays as its arguments.

    • We start by mapping through the elements inside the main array. Meaning each one of the inner arrays.
    • Now the need a callback function to find the max of each inner array provided by the map.
  • So we want to create a function that does the work of Math.max and accepts input as an array (which by it doesn’t by default).

  • In other words, it would be really nice and simple if this worked by itself: Math.max([9, 43, 20, 6]); // Resulting in 43

  • Alas, it doesn’t.

    • To do the work of accepting arguments in the shape of an array, there is this Function.prototype.apply method, but it complicates things a bit by invoking the context function.
  • i.e. Math.max.apply(null, [9, 43, 20, 6]); would invoke something like a Max.max method. What we’re looking for… almost.

  • Here we’re passing null as the context of the Function.prototype.apply method as Math.max doesn’t need any context.

    • Since arr.map expects a callback function, not just an expression, we create a function out of the previous expression by using the Function.bind method.
    • Since, Function.prototype.apply is a static method of the same Function object, we can call Function.prototype.bind on Function.prototype.apply i.e. Function.prototype.apply.bind.
    • Now we pass the context for the Function.prototype.apply.bind call (in this case we want Math.max so we can gain its functionality).
    • Since the embedded Function.prototype.apply method will also require a context as it’s 1st argument, we need to pass it a bogus context.
      • So, we pass null as the 2nd param to Function.prototype.apply.bind which gives a context to the Math.max method.

      • Since, Math.max is independent of any context, hence, it ignores the bogus context given by Function.prototype.apply method call.

      • Thus, our Function.prototype.apply.bind(Math.max, null) makes a new function accepting the arr.map values i.e. the inner arrays.

  • Relevant Links

Solution 4:

function largestOfFour(arr, finalArr = []) {
  return !arr.length
    ? finalArr
    : largestOfFour(arr.slice(1), finalArr.concat(Math.max(...arr[0])))
}

Basic Algorithm Scripting: Confirm the Ending

  • Check if a string (first argument, str) ends with the given target string (second argument, target).

  • This challenge can be solved with the .endsWith() method, which was introduced in ES2015. But for the purpose of this challenge, we would like you to use one of the JavaScript substring methods instead.

Solution 1:

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

confirmEnding("Bastian", "n");

Solution 1, Code Explanation

  • First we use the slice method copy the string.
  • In order to get the last characters in str equivalent to the target's length we use the slice method.
  • The first parameter inside the slice method is the starting index and the second parameter would be the ending index.
  • For example str.slice(10, 17) would return give me.
  • In this case we only include one parameter which it will copy everything from the starting index.
  • We substract the length of str and the length of target, that way, we shall get the last remaining characters equivalent to the target's length.
  • Finally we compare the return result of slice to target and check if they have the same characters.

Solution 2:

function confirmEnding(str, target) {
  let re = new RegExp(target + "$", "i");
  return re.test(str);
}

console.log(confirmEnding("Bastian", "n"));

Solution 2, Code Explanation

  • We need to make a pattern from the target variable that exists at the end of the string str.
  • Since we will use a variable that will change the pattern each time the function is called, we will use the constructor of the regular expression object new RegExp(pattern[, flags]), so we start with: new RegExp(target).
  • Then we have to check at the end of the string, so we concatenate to the target variable the $ character to match the end: new RegExp(target+'$').
  • We use the flag i to ignore the case of the pattern and we have our completed RegExp: new RegExp(target+'$','i'), or we can ommit the flag entirely.
  • Finally, we are using our regular expression with the test method to the given string, to check if the string ends with the pattern and return true or false accordingly.

Basic Algorithm Scripting: Repeat a String

  • Repeat a given string str (first argument) for num times (second argument). Return an empty string if num is not a positive number.

My Solution:

function repeatStringNumTimes(str, num) {
  let arr = ""
  if (num > 0) {
    for (let i = 0; i < num; i++ ) {
    arr += str;
    }
  } else {
    arr ="";
  }
  return arr;
}

repeatStringNumTimes("abc", 3);

Solution 1:

function repeatStringNumTimes(str, num) {
  var accumulatedStr = "";

  while (num > 0) {
    accumulatedStr += str;
    num--;
  }

  return accumulatedStr;
}

Solution 2:

function repeatStringNumTimes(str, num) {
  if (num < 1) {
    return "";
  } else if (num === 1) {
    return str;
  } else {
    return str + repeatStringNumTimes(str, num - 1);
  }
}

Solution 2, Code Explanation

  • This solution uses recursion.
  • We check if num is negative and return an empty string if true.
  • Then we check if it’s equal to 1 and in that case we return the string itself.
  • If not, we add the string to a call of our function with num being decreased by 1, which will add another str and another… until eventually num is 1. And return that whole process.

Solution 3:

function repeatStringNumTimes(str, num) {
  return num > 0 ? str.repeat(num) : "";
}

repeatStringNumTimes("abc", 3);

Solution 4:

function repeatStringNumTimes(str, num) {
  return num > 0 ? str + repeatStringNumTimes(str, num - 1) : '';
}

Basic Algorithm Scripting: Truncate a String

  • Truncate a string (first argument) if it is longer than the given maximum string length (second argument). Return the truncated string with a ... ending.

My Solution 1:

function truncateString(str, num) {
   if (num >= str.length){
     return str;
   } else {
     return str.slice(0,num)+"...";
   }  
}

truncateString("A-tisket a-tasket A green and yellow basket", 8);

My Solution 2:

function truncateString(str, num) {
  return num >= str.length ? str:str.slice(0,num)+"...";
}
truncateString("A-tisket a-tasket A green and yellow basket", 8);

Solution 1:

function truncateString(str, num) {
  // Clear out that junk in your trunk
  if (str.length > num) {
    return str.slice(0, num) + "...";
  } else {
    return str;
  }
}

Solution 1, Code Explanation

  • We start off with a simple if statement to determine one of two outcomes…
  • If our string length is greater than the num we want to truncate it, we return a slice of our string starting at character 0, and ending at num. We then append our '...' to the end of the string.
  • However, if above situation is not true, it means our string length is less than our truncation num. Therefore, we can just return the string.

Solution 2:

function truncateString(str, num) {
  return str.length > num ? str.slice(0, num) + "..." : str;
}

Solution 2, Code Explanation

  • This solution is very similar to basic solution. To determine the new string, we use a ternary operator. In our ternary operation, if str.length is larger than num, we return a new string which is slice of our string starting at character 0, and ending at num and the '...' is appended to the end of our new string. If str.length is less than or equal to num, we return the string without any truncation. m
  • NOTE In order to understand the above code, you need to understand how a Ternary Operator works. The Ternary Operator is frequently used as a shortcut for the if statement and follows this format: condition ? expr1 : expr2. If the condition evaluates to true, the operator returns the value of expr1. Otherwise, it returns the value of expr2.

Basic Algorithm Scripting: Finders Keepers

  • Create a function that looks through an array (first argument) and returns the first element in the array that passes a truth test (second argument). If no element passes the test, return undefined.
  • findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; }) should return 8.
  • findElement([1, 3, 5, 9], function(num) { return num % 2 === 0; }) should return undefined.

Solution 1:

function findElement(arr, func) {
  let num = 0;

  for (var i = 0; i < arr.length; i++) {
    num = arr[i];
    if (func(num)) {
      return num;
    }
  }

  return undefined;
}

findElement([1, 2, 3, 4], num => num % 2 === 0);

Solution 1, Code Explanation

  • Challenge asks us to look through array. This is done using a for loop.
  • The num variable is being passed into the function, so we set it to each index in our array.
  • The pre-defined function already checks each number for us, so if it is “true”, we return that num.
  • If none of the numbers in the array pass the function’s test, we return undefined.

Solution 2:

function findElement(arr, func) {
  return arr.find(func);
}

Solution 3:

function findElement(arr, func) {
  return arr[arr.map(func).indexOf(true)];
}
  • Look through the array given in the 1st paramater “arr” using the .map() method
  • Use the function in the 2nd parameter as the callback function in arr.map()
  • Acquire the index of the first number that meets the condition in the function.
  • Use that index to display the first available number that meets the condition.

Basic Algorithm Scripting: Boo who

  • Check if a value is classified as a boolean primitive. Return true or false.
  • booWho(true) should return true.
  • booWho(false) should return true.
  • booWho(NaN) should return false.
  • booWho("true") should return false.
function booWho(bool) {
  return typeof bool === "boolean";
}

booWho(null);

Basic Algorithm Scripting: Title Case a Sentence

  • Return the provided string with the first letter of each word capitalized. Make sure the rest of the word is in lower case.

  • For the purpose of this exercise, you should also capitalize connecting words like "the" and "of".

Solution 1:

String.prototype.replaceAt = function(index, character) {
  return (
    this.substr(0, index) + character + this.substr(index + character.length)
  );
};

function titleCase(str) {
  var newTitle = str.split(" ");
  var updatedTitle = [];
  for (var st in newTitle) {
    updatedTitle[st] = newTitle[st]
      .toLowerCase()
      .replaceAt(0, newTitle[st].charAt(0).toUpperCase());
  }
  return updatedTitle.join(" ");
}

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

Solution 1, Code Explanatin

  • We are modifying the replaceAt function using prototype to facilitate the use of the program.

  • Split the string by white spaces, and create a variable to track the updated title. Then we use a loop to turn turn the first character of the word to uppercase and the rest to lowercase. by creating concatenated string composed of the whole word in lowercase with the first character replaced by its uppercase.

Solution 2:

function titleCase(str) {
  var convertToArray = str.toLowerCase().split(" ");
  var result = convertToArray.map(function(val) {
    return val.replace(val.charAt(0), val.charAt(0).toUpperCase());
  });
  return result.join(" ");
}

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

Solution 3:

function titleCase(str) {
  return str.toLowerCase().replace(/(^|\s)\S/g, L => L.toUpperCase());
}

Solution 3, Code Explanation

The solution works by first lowercasing all the characters in the string and then only uppercasing the first character of each word.

  • Lowercase the whole string using str.toLowerCase().

  • Replace every word’ first character to uppercase using .replace.

  • Search for character at the beginning of each word i.e. matching any character following a space or matching the first character of the whole string, by using the following pattern.

  • Regex explanation:

  • Find all non-whitespace characters (\S)

  • At the beginning of string (^)

  • Or after any whitespace character (\s)

    • The g modifier searches for other such word pattern in the whole string and replaces them.
    • This solution works with national symbols and accented letters as illustrated by following examples
      • international characters: ‘бабушка курит трубку’ // -> ‘Бабушка Курит Трубку’
      • accented characters: ‘località àtilacol’ // -> ‘Località Àtilacol’
  • JS Regex Resources

Basic Algorithm Scripting: Slice and Splice

  • You are given two arrays and an index. Use the array methods slice and splice to copy each element of the first array into the second array, in order. Begin inserting elements at index n of the second array. Return the resulting array. The input arrays should remain the same after the function runs.
  • frankenSplice([1, 2, 3], [4, 5], 1) should return [4, 1, 2, 3, 5].
  • frankenSplice(["claw", "tentacle"], ["head", "shoulders", "knees", "toes"], 2) should return ["head", "shoulders", "claw", "tentacle", "knees", "toes"].
  • The first and second arrays should remain the same after the function runs.

Solution 1:

function frankenSplice(arr1, arr2, n) {
  let localArray = arr2.slice();
  for (let i = 0; i < arr1.length; i++) {
    localArray.splice(n, 0, arr1[i]);
    n++;
  }
  return localArray;
}

frankenSplice([1, 2, 3] , [4, 5, 6], 1);

Solution 1, Code Explanation

  • Our goal is to take all of the elements from arr1 and insert them into arr2 starting with index position n. At the same time we must ensure that neither arr or arr2 have been mutated.

  • Using the slice() function we can create an exact replica of arr2 and assign the result of the operation to a variable, localArray.

  • Now that we have an array that we can mutate on, we can iterate through every item in the first array. For each item in the first array we can use the splice() function to insert the item into index n of localArray.

  • We increment the index n by one. This will ensure that every item from the arr1 is inserted into localArray in the proper index position.

  • Finally, we return the localArray and end the function.

Solutio 2:

function frankenSplice(arr1, arr2, n) {
  let localArr = arr2.slice();
  localArr.splice(n, 0, ...arr1);
  return localArr;
}

Solution 2, Code Explanation

  • Since our goal is to return the new array with out altering arr1 or arr2 we create a localArr and add all the items from arr2 using the slice() function

  • Since the splice() function will mutate (alter) arrays and can be used to add new elements we will use it to add the contents of arr1 into localArr. n is the starting position where our content will be inserted. We won’t be deleting any elements so the next argument is 0. Then we add the entire contents of arr1 using spread syntax ....

  • localArr is returned and the function is complete.

Basic Algorithm Scripting: Falsy Bouncer

  • Remove all falsy values from an array.

  • Falsy values in JavaScript are false, null, 0, "", undefined, and NaN.

  • Hint: Try converting each value to a Boolean.

  • Relevant Links: Falsy Values

Solution 1:

function bouncer(arr) {
  let newArray = [];
  for (var i = 0; i < arr.length; i++) {
    if (arr[i]) newArray.push(arr[i]);
  }
  return newArray;
}

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

Solution 2:

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

Solution 2, Code Explanation

  • The Array.prototype.filter method expects a function that returns a Boolean value which takes a single argument and returns true for truthy value or false for falsy value. Hence we pass the built-in Boolean function.

Basic Algorithm Scripting: Where do I Belong

  • Return the lowest index at which a value (second argument) should be inserted into an array (first argument) once it has been sorted. The returned value should be a number.
  • For example, getIndexToIns([1,2,3,4], 1.5) should return 1 because it is greater than 1 (index 0), but less than 2 (index 1).
  • Likewise, getIndexToIns([20,3,5], 19) should return 2 because once the array has been sorted it will look like [3,5,20] and 19 is less than 20 (index 2) and greater than 5 (index 1).

Solution 1:

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 a;
  }

  return arr.length;
}

Solution 1, Code Explanation

  • First I sort the array using .sort(callbackFunction) to sort it by lowest to highest, from left to right.
  • Then I use a for loop to compare the items in the array starting from the smallest one. When an item on the array is greater than the number we are comparing against, then we return the index as an integer.

Solution 2:

function getIndexToIns(arr, num) {
  // Find my place in this sorted array.
  var times = arr.length; // runs the for loop once for each thing in the array
  var count = 0;
  for (var i = 0; i < times; i++) {
    if (num > arr[i]) {
      count++;
    }
  } // counts how many array numbers are smaller than num
  return count; // the above equals num's position in a sorted array
}

getIndexToIns([40, 60], 50);

Solution 2, Code Explanation

- I do not sort the arr input array
- I run a for loop counting whenever the num input is bigger than an arr input number.
- This number is equivalent to what num’s position would be in a sorted array.

Solution 3:

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

  var i = 0;
  while (num > arr[i]) {
    i++;
  }

  return i;
}

getIndexToIns([40, 60], 50);

Solution 4:

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

Solution 4, CodeEXplanation

  • First we add the number num to the array using push() which adds it as the last element of the array.
  • Then we use sort() with the callback function function(a, b){return a-b} to sort the numbers in ascending order.
  • Lastly we return the postion or index of num in the array with the indexOf() function.

Solution 5:

function getIndexToIns(arr, num) {
  // sort and find right index
  var index = arr
    .sort((curr, next) => curr - next)
    .findIndex(currNum => num <= currNum);
  // Returns proper answer
  return index === -1 ? arr.length : index;
}

getIndexToIns([40, 60], 500);

Solution 5, Code Explanation

  • First sort the array in ascending order, this is currently done using array functions for minimal footprint.
  • Once the array it is sorted, we directly apply the .findIndex() where we are going to compare every element in the array until we find where num <= currNum meaning where the number we want to insert is less or equal to the current number number in the iteration.
  • Then we use ternary operations to check whether we got an index returned or -1. We only get -1 when the index was not found meaning when we get a false for all elements int he array, and for such case, it would mean that num should be inserted at the end of the list hence why we use arr.length.
  • Array.findIndex()
  • Arrow Functions

Solution 6:

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

getIndexToIns([1, 3, 4], 2);

Solution 7:

function getIndexToIns(arr, num) {
  return arr.filter(val => num > val).length;
}

Basic Algorithm Scripting: Mutations

  • Return true if the string in the first element of the array contains all of the letters of the string in the second element of the array.
  • mutation(["hello", "Hello"]) should return true.
  • mutation(["hello", "neo"]) should return false.

Solution 1:

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

Solution 1, Code Explanation

  • First we make the two strings in the array lowercase. test will hold what we are looking for in target.
  • Then we loop through our test characters and if any of them is not found we return false.
  • If they are all found, the loop will finish without returning anything and we get to return true.

Solution 2:

function mutation(arr) {
  return arr[1]
    .toLowerCase()
    .split("")
    .every(function(letter) {
      return arr[0].toLowerCase().indexOf(letter) != -1;
    });
}

Solution 2, Code Explanation

  • Grab the second string, lowercase and turn it into an array; then make sure every one of its letters is a part of the lowercased first string.

  • Every will basically give you letter by letter to compare, which we do by using indexOf on the first string. indexOf will give you -1 if the current letter is missing. We check that not to be the case, for if this happens even once every will be false.

Solution 3

function mutation([ target, test ], i = 0) {
  target = target.toLowerCase();
  test = test.toLowerCase();
  return i >= test.length
    ? true
    : !target.includes(test[i])
      ? false
      : mutation([ target, test ], i + 1);
}

Basic Algorithm Scripting: Chunky Monkey

  • Write a function that splits an array (first argument) into groups the length of size (second argument) and returns them as a two-dimensional array.

My solution:

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

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

Code Explanation

First, we create an empty array arr2 where we will store our ‘chunks’. The for loop starts at zero, increments by size each time through the loop, and stops when it reaches arr.length. Note that this for loop does not loop through arr. Instead, we are using the loop to generate numbers we can use as indices to slice the array in the right locations. Inside our loop, we create each chunk using arr.slice(i, i+size), and add this value to arr2 with arr2.push(). Finally, we return the value of arr2.

Solution 1:

function chunkArrayInGroups(arr, size) {
  var temp = [];
  var result = [];

  for (var a = 0; a < arr.length; a++) {
    if (a % size !== size - 1) temp.push(arr[a]);
    else {
      temp.push(arr[a]);
      result.push(temp);
      temp = [];
    }
  }

  if (temp.length !== 0) result.push(temp);
  return result;
}

Solution 1, Code Explanation

  • Firstly, we create two empty arrays called temp and result, which we will eventually return.
  • Our for loop loops until a is equal to or more than the length of the array in our test.
  • Inside our loop, we push to temp using temp.push(arr[a]); if the remainder of a / size is not equal to size - 1.
  • Otherwise, we push to temp, push temp to the result variable and reset temp to an empty array.
  • Next, if temp isn’t an empty array, we push it to result.
  • Finally, we return the value of result.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment