;

Javascript Algorithm Scripting

Listed are a number of sets of algorithm scripts I have worked on, the functions that I have created aren't necessarily the correct or fastest way to achieve the objective, nevertheless they are all fully functional and showcase my ability to code in javascript.

I intend to go back over them to improve the coding, I shall include my original code and the updated code to show my natural progression.

The scripts are taken from FreeCodeCamp.

Intermediate Algorithm Scripting

#1 : Sum all numbers in a range

Objective: Return the sum of two numbers and all numbers between them. The lowest number does not need to come first.

The code:

function sumAll(arr) {
  var max = Math.max(arr[0], arr[1]);
  var min = Math.min(arr[0], arr[1]);
  
  var arrValues = [];
  
  while (min !== max){
    arrValues.push(min);
    min += 1;
  }
  arrValues.push(max);
  
  var totalSum = arrValues.reduce(function(previousValue, currentValue){
    return previousValue + currentValue;
  });
  return totalSum;
}

sumAll(arr);

Notes: Provide two values seperated by a comma

Input:

Output:

#2 : Difference of two arrays

Objective: Compare two arrays and return a new array with any items only found in one of the two given arrays, but not both. In other words, return the symmetric difference of the two arrays.

The code:

function diffArray(arr1, arr2) {
  var newArr = []; 

  for (var j = 0; j < arr2.length; j ++){
    if (arr1.indexOf(arr2[j]) === -1){
      newArr.push(arr2[j]);
    }
  }
  
  for (var i = 0; i < arr1.length; i ++){
    if (arr2.indexOf(arr1[i]) === -1){
      newArr.push(arr1[i]);
    }
  }
  
  return newArr;
}

diffArray(arr1, arr2);

Notes: Provide any number of values for each array seperated by commas

Input:

Array One:
Array Two:

Output:

#3 : Roman numeral converter

Objective: Convert the given number into a roman numeral.

The code:

function convertToRoman(num) {
  var units = num % 10;
  var tens = Math.floor((num % 100) / 10 );
  var hundreds = Math.floor((num % 1000) / 100 );
  var thousands = Math.floor((num % 10000) / 1000 );
  var romanArr = [];
  
  switch (thousands){
    case 1: 
      romanArr.push('M');
      break;
    case 2: 
      romanArr.push('MM');
      break;
    case 3: 
      romanArr.push('MMM');
      break;
    case 4: 
      romanArr.push('MMMM');
      break;
  }
  
  switch (hundreds){
    case 1: 
      romanArr.push('C');
      break;
    case 2: 
      romanArr.push('CC');
      break;
    case 3: 
      romanArr.push('CCC');
      break;
    case 4: 
      romanArr.push('CD');
      break;
    case 5: 
      romanArr.push('D');
      break;
    case 6: 
      romanArr.push('DC');
      break;
    case 7: 
      romanArr.push('DCC');
      break;
    case 8: 
      romanArr.push('DCCC');
      break;
    case 9: 
      romanArr.push('CM');
      break;
  }
  
  switch (tens){
    case 1: 
      romanArr.push('X');
      break;
    case 2: 
      romanArr.push('XX');
      break;
    case 3: 
      romanArr.push('XXX');
      break;
    case 4: 
      romanArr.push('XL');
      break;
    case 5: 
      romanArr.push('L');
      break;
    case 6: 
      romanArr.push('LX');
      break;
    case 7: 
      romanArr.push('LXX');
      break;
    case 8: 
      romanArr.push('LXXX');
      break;
    case 9: 
      romanArr.push('XC');
      break;
  }
  
  switch (units){
    case 1: 
      romanArr.push('I');
      break;
    case 2: 
      romanArr.push('II');
      break;
    case 3: 
      romanArr.push('III');
      break;
    case 4: 
      romanArr.push('IV');
      break;
    case 5: 
      romanArr.push('V');
      break;
    case 6: 
      romanArr.push('VI');
      break;
    case 7: 
      romanArr.push('VII');
      break;
    case 8: 
      romanArr.push('VIII');
      break;
    case 9: 
      romanArr.push('IX');
      break;
  }
  
  return romanArr.join('');
}

convertToRoman(num);
***** UPDATED 16th October 2016 *****

function convertToRoman(num) {
  var roman = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'];
  var numeric = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
  
  var result = '';  
  var length = numeric.length; 
  
  for (var i = 0; i < length; i ++){
    while (num >= numeric[i]){
      result += roman[i];
      num -= numeric[i];
    }
  }
  
  return result;
}

convertToRoman(num);

Input:

Output:

#4 : Wherefore art thou

Objective: Make a function that looks through an array of objects (first argument) and returns an array of all objects that have matching property and value pairs (second argument). Each property and value pair of the source object has to be present in the object from the collection if it is to be included in the returned array.

The code:

function whatIsInAName(collection, source) {
  var results = [];
  
  for (var i = 0; i < collection.length; i++) {  
  var flag = true; 
    for (var collProp in collection[i]) {
	  for (var sourceProp in source) {
        if (collection[i].hasOwnProperty(sourceProp) === false) {
          flag = false;
        } else if (source[sourceProp] != collection[i][sourceProp] ) {
          flag = false;
        }
      } 
    }

    if (flag === true){
      results.push(collection[i]);
    }
  }
  
  return results;
}

whatIsInAName(collection, source);

Input:

Collection: { first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }

Source: { last: "Capulet" }

Output:

#5 : Search and replace

Objective:

The code



			
			
			

Input:

Output:

#6 : Pig Latin

Objective:

The code



			
			
			

Input:

Output:

#7 : DNA Pairing

Objective:

The code



			
			
			

Input:

Output:

#8 : Missing letters

Objective:

The code



			
			
			

Input:

Output:

#9 : Boo who

Objective:

The code



			
			
			

Input:

Output:

#10 : Sorted union

Objective:

The code



			
			
			

Input:

Output:

#11 : Convert HTML entities

Objective:

The code



			
			
			

Input:

Output:

#12 : Spinal tap case

Objective:

The code



			
			
			

Input:

Output:

#13 : Sum all odd Fibonacci numbers

Objective:

The code



			
			
			

Input:

Output:

#14 : Sum all prime numbers

Objective:

The code



			
			
			

Input:

Output:

#15 : Smallest common multiple

Objective:

The code



			
			
			

Input:

Output:

#16 : Finders keepers

Objective:

The code



			
			
			

Input:

Output:

#17 : Drop it

Objective:

The code



			
			
			

Input:

Output:

#18 : Steamroller

Objective:

The code



			
			
			

Input:

Output:

#19 : Binary agents

Objective:

The code



			
			
			

Input:

Output:

#20 : Everything be true

Objective:

The code



			
			
			

Input:

Output:

#21 : Arguments optional

Objective:

The code



			
			
			

Input:

Output:

Basic Algorithm Scripting

#1 : Reverse a string

Objective: Take a given string and output it's reverse.

The code:

function reverseString(str) {
  reversed = str.split('').reverse().join('');
  
  return reversed;
}

reverseString(str);

Input:

Output:

#2 : Factorialize a number

Objective: If an 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

The code:

function factorialize(num) {
  var result = num;
  
  if (num == 0) {
    return 1;
  } else {
	for (var i = 1; i < num; i ++){
	  result = result * i; 
	}
  }
  
  return result;
}

factorialize(num);

Input:

Output:

#3 : Check for palindromes

Objective: Checks a word or sentence to see if it's spelled the same way both forward and backward, ignoring punctuation, case, and spacing.

The code:

function palindrome(str) {
  strToArray = str.toLowerCase().match(/[a-z0-9]/g); 
  reversedStr = str.toLowerCase().match(/[a-z0-9]/g).reverse();

  for (i = 0; i < strToArray.length; i ++){
	if (strToArray[i] !== reversedStr[i]) {
	  return false;
	}
  }
	
  return true;
}

palindrome(str);

Input:

Output:

#4 : Find the longest word in a string

Objective: Return the length of the longest word in the inputted sentence.

The code:

function findLongestWord(str) {
  var stringToArray = str.split(" ");
  var longestWord = 0;

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

findLongestWord(str);

Input:

Output:

#5 : Title case a sentence

Objective: Return the provided string with the first letter of each word capitalized. Making sure the rest of the word is in lower case.

The code:

function titleCase(sentence) {
  var arrayOfSentence = sentence.split(" ");
  var arrayOfCapitalisedSentence = [];
  
  for (var i = 0; i < arrayOfSentence.length; i ++){
    var capital = arrayOfSentence[i].charAt(0).toUpperCase();
    var arrayOfWord = arrayOfSentence[i].toLowerCase().split("");
    arrayOfWord.splice(0, 1, capital);
    var newWord = arrayOfWord.join("");
    arrayOfCapitalisedSentence.push(newWord);
  }
  
  var capitalisedSentence = arrayOfCapitalisedSentence.join(" ");
  return capitalisedSentence;
}

titleCase(sentence);

Input:

Output:

#6 : Return largest numbers in arrays

Objective: Return an array consisting of the largest number from each provided sub-array.

The code:

function sortAndPick(array) {
  var finalArray = [];
  
  for (var i = 0; i < array.length; i ++){
    array[i].sort(function(a, b){return a-b;});
    finalArray.push(array[i][array.length - 1]);
  }
  
  return finalArray;
}

sortAndPick(array);

Input:

Array One:
Array Two:
Array Three:
Array Four:

Output:

#7 : Confirm the ending

Objective: Check if a string (sentence) ends with the given target string, without using the endsWith() method.

The code:

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

confirmEnding(str, target);

Input:

Sentence:
Ending string:

Output:

#8 : Repeat a string

Objective: Repeat a given string a certain number of times. Return an empty string if number is not a positive number.

The code:

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

repeatStringNumTimes(str, num);

Input:

String:
Multiple:

Output:

#9 : Truncate a string

Objective: Truncate a string if it is longer than the given maximum string length. Return the truncated string with a ... ending.

Note that the three dots inserted to the end should be included in the maximum string length.

However, if the given maximum string length is less than or equal to 3, then the addition of the three dots does not add to the maximum string length.

The code:

function truncateString(str, num) {
  if (num <= 3){
    newStr = str.slice(0, num);
    newStr = newStr.concat("...");
  } else if (num < str.length){
    newStr = str.slice(0, num - 3);
    newStr = newStr.concat("...");
  } else {
    newStr = str;
  }
  
  return newStr;
}

truncateString(str, num);

Input:

String
Max string length

Output:

#10 : Chunky Monkey

Objective: Write a function that splits an array into groups the length of size specified and returns them as a multi-dimensional array.

The code:

function chunkArrayInGroups(arr, size) {
  var returnArray = [];
  
  while (arr.length > 0){
    newArray = arr.splice(0, size);
    returnArray.push(newArray);     
  }
  
  return returnArray;
}

chunkArrayInGroups(arr, size);

Input:

Array:
Size of new arrays:

Note: Open Console to see multi-dimensional array output.

Output:

#11 : Slasher flick

Objective: Return the remaining elements of an array after chopping off n elements from the beginning.

The code:

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

slasher(arr, howMany);

Input:

Array:
No. of elements to remove:

Output:

#12 : Mutations

Objective: 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.

The code:

function mutation(strArray) {
  var first = strArray[0].toLowerCase();
  var second = strArray[1].toLowerCase();

  for (var i = 0; i < second.length; i ++){
    strArray = first.indexOf(second[i]);
    if (strArray === -1){
      strArray = false;
      break;
    } else {
      strArray = true;
    }
  }
  return strArray;
}

mutation([string, string]);

Input:

First String:
Second string:

Output:

#13 : Falsy bouncer

Objective: Remove all false values from an array.

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

The code:

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

bouncer(arr);

Input: Array to be passed: [1, null, NaN, 2, undefined, 3, 0, false, 4, ""]

Output:

#14 : Seek and destroy

Objective: Remove all elements from the initial array that are of the same value as the reamining arguments.

The code:

function destroyer(arr) {
  var args = Array.from(arguments);
  
  var result = arr.filter(function (value,index,array) {
    if (args.indexOf(value) === -1){
      return true;
    }
  });
  return result;
}

destroyer(arr,args);

Input:

Array:
Arguments:

Output:

#15 : Where do I belong

Objective: 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.

The code:

function getIndexToIns(arr, num) {
  arr.sort(function(a, b){return a-b;});
  
  var index = arr.findIndex(function(value){
    return value >= num;
  });
  
  if (index !== -1){
    return index;
  } else {
    return arr.length;
  }
}

getIndexToIns(arr, num);

Input:

Array:
Value to insert:

Output:

#16 : Caesars Cipher

Objective: Write a function which takes a ROT13 encoded string as input and returns a decoded string.

One of the simplest and most widely known ciphers is a Caesar cipher, also known as a shift cipher. In a shift cipher the meanings of the letters are shifted by some set amount.

A common modern use is the ROT13 cipher, where the values of the letters are shifted by 13 places. Thus 'A' ↔ 'N', 'B' ↔ 'O' and so on.

The code:

function rot13(str) { 
  changeToCharCodes = [];
  changeToStrChars = [];
  
  for (var i = 0; i < str.length; i ++){
    changeToCharCodes.push(str.charCodeAt(i));
    if (changeToCharCodes[i] >= 65 && changeToCharCodes[i] <= 77) {
      changeToCharCodes[i] += 13;
    } else if (changeToCharCodes[i] >= 78){
      changeToCharCodes[i] -= 13;
    } 
    changeToStrChars.push(String.fromCharCode(changeToCharCodes[i]));
  }
  
  convertToStr = changeToStrChars.join("");
 
  return convertToStr;
  
}

rot13(str);

All letters should be uppercase.

Input:

Output: