Introduction

Algorithm is simply a set of step by step procedures for solving a complex problem by splitting its large chunk into several smaller bits and solving them procedurally, which can then be tackled individually in steps to solve the original problem

Algorithms can be implemented practically with the use of one or more programming langauges. This documentation in an insight to a few algorithms problems and my approach to solving them by enumerating step by step, the procedures I took to arive at my solution. These steps might not be the shortest possible path or most consise pattern, but is aimed at exposing the process step by step in the most plain way possible.

Before proceeding I will want to point out some of the types of algorithms that probably might have been used, and give a brief definition on each.


Types of Algorithms

Some types of algorithms include, but are not restricted to the following

  1. Backtracking algorithms – This algorithm pattern involves dividing the problem into subproblems, each which can be attempted to be solved, but however, if the desired solution is not reached, steps are retraced backwards in the problem until a path is found that moves it forward.
  2. Randomized algorithms – This kind of algorithm makes use a random number at least once during the computation to find a solution to the problem.
  3. Divide and conquer algorithms – This type of algorithm involves the division of the problem into smaller subproblems of the same type, solving these smaller problems, and then cummulating their solutions to solve the original problem.
  4. Recursive algorithms – This type of algorithm solves the lowest and simplest version of a problem to then solve increasingly larger versions of the problem until the solution to the original problem is found.
  5. Brute force algorithms – This type of algorithm tries all possible solutions to a problem until a satisfactory solution is found.
  6. Dynamic programming algorithms – This type of algorithm involves the breaking of a complex problem into a collection of simpler subproblems, then solve each of those subproblems only once, and storing their solution for future use instead of re-computing their solutions.
  7. Greedy algorithms – This kind of algorithm involves finding an optimal solution at the local level with the intent of finding an optimal solution for the whole problem.

It is important to learn the use and applicaton of Algorithms for some the folowing reasons

  1. Enables the easy breaking down of complex problems into smaller bits
  2. Improves the efficiency of solving a problem
  3. It enables the propert utilization of resources avaliable to solve a problem
  4. It provides clarity of the problem statement
  5. Saves time and improves precison

Below are some algorithm problems I solved using plain JavaScript, with some commented details, and my thought process on how I went about my solution.



ROT13 Caeser Cipher Decoder

This is a program that accepts an encoded ROT13 text and converts it back to its original text.
The ROT13 is a simple letter substitution cipher that replaces a letter with the 13th letter after it in the alphabet.

                        
function rot13(str) {
  /** Defining a regex pattern rule */
  const regex = /[A-Z]/ig
    
  /** Splitting the input string argument into an array of characters */
  const splString = str.split('')
    
  /** Defining an empty array to hold the character codes of each character */
  let charCodeArr = []
    
  /** Iterating through each of the characters, ,  */
  for(let i = 0; i < splString.length; i++){

    /** Testing each character against the regular expression defined */
    if(splString[i].match(regex)){

      /** Adding 13 to each character code withing the range of A - M and inserting its result into the empty array */
      if(splString[i].charCodeAt() >= 65 && splString[i].charCodeAt() <= 77){
        charCodeArr.push(`${splString[i].charCodeAt()+13}`)
      }
      
      /** Subtracting 13 from each character code within the range of N - Z and inserting its result into the empty array */
      else{
        charCodeArr.push(`${splString[i].charCodeAt()-13}`)
      }      
    }
    
    /** Inserting any non alphanumeric character without any form of modification */
    else{
      charCodeArr.push(splString[i])
    }
  }
    
  /** Initializing a variable to hold the final result */
  let rot13String = ''
    

  /** Populating the final result with the converted character codes together with non-alphanumeric characters at appropriate positions */
  for(let i = 0; i < charCodeArr.length; i++){
    if(splString[i].match(regex)){
      rot13String += String.fromCharCode(Number(charCodeArr[i]))
    }else{
      rot13String += charCodeArr[i]
    }
  }
    
  /** Returning the final result of the operations */
  return rot13String;
}
    
/** Testing the Function with a ROT13 encoded text. Output is "FREE PIZZA!" */
rot13("SERR CVMMN!");
                    

My Thought Process



Sum In Range

This program makes use of algorithm to get the sum of two numbers together with the sum of all numbers in-between them

        
function sumAll(arr) {br
  /** Summing the two numbers in the given array */
  const sumArr = arr[0] + arr[1];
  
  /** Sorting the array to ensure that the lowest number comes first */
  const sortedArr = arr.sort((a, b)=> a - b );
  
  /** Obtaining an array containing all the numbers between the two gven numbers */
  let arrRange = [];
  let sortedMinArrPlusOne = sortedArr[0] + 1
  for(let i = sortedArr[0]; i < sortedArr[1] - 1; i++){
    arrRange.push(sortedMinArrPlusOne++);
  }
  
  /** Adding all the numbers between the two given numbers */
  let summedArrRange = 0;
  for(let i = 0; i < arrRange.length; i++){
    summedArrRange += arrRange[i];
  }
  
  /** Summing the sum of the two numbers and the range of numbers between them */
  const totalSum = sumArr + summedArrRange;
  
  console.log(totalSum) // Printing the final answer
  return totalSum;
}
    
/** Calling the Function with input arguments */
sumAll([4, 9]);
    

My Thought Process



Average Altitude To Orbital Period

This is a program that accepts an array or objects containing an entity and its average height, and returns a new object for the entity and its orbital period

                    
function orbitalPeriod(arr) {

  /** Initialization of an array to hold the values of the objects to be created. */
  const newArr = []

  /** The actual Function that takes the average altitude and converts it to orbital period */
  function getOrbitalPeriod(avgAlt){
    const GM = 398600.4418;
    const earthRadius = 6367.4447;
    const orbitalRadius = earthRadius + avgAlt

    /** Formula for calculation */
    return Math.round(
      2 * Math.PI * Math.sqrt(((orbitalRadius * orbitalRadius) * orbitalRadius) / GM)
    )
  }

  /** Iterating through the given array to obtain their values of average height, calculate their orbital height, and store the values in the newly created object */
  for(let i = 0; i < arr.length; i++){
    let tempVal = {
      name: arr[i]['name'],
      orbitalPeriod: getOrbitalPeriod(arr[i]['avgAlt'])
    }

    /** Inserting the newly created objects into the declared empty array above. */
    newArr.push(tempVal)

  }
)

  /** Returning the new object array */
  return newArr;
}

/** Testing the Function with an array with a single object, containing its name and average height value. */
orbitalPeriod([{name : "manjaro", avgAlt : 35873.5553}]);

/** result is [ { name: 'manjaro', orbitalPeriod: 86400 } ] */
                  

My Thought Process



Find The Missing Letter

This program spots out a missing character from amongst a string of characters, and returns the missing character, by comparing their ASCII unicode

        
function findTheMissingLetter(str) {

  for(let i = 0; i < str.length; i++){
    if(str.charCodeAt(i) !== (str.charCodeAt(0) + i)){
      return String.fromCharCode(str.charCodeAt(i)-1)
    }
  }

  return undefined;
}
  
/** The character "d" is Returned */
findTheMissingLetter("abce");
 
    

My Thought Process



Palindrome Checker

A palindrome is simply a word whoose character arrangement is the same when spelt normally (forward) and backwards. The function below, takes a string as input arguent strips it of all non alphanumeric characters, removes all spaces flips it backward and compares the processed string with itself spelt backwards, and returns true or false if it is a palindrome or not

                        
/** Removing all non alphanumeric characters and spaces */
function removeNonAlphaNumericAndJoin(arg){
    const regex = /[^\W]/ig
    return arg.match(regex).join("")
}

/** The palindrome checker function */
function palindrome(str){
    /** Variable to hold the reversed version of the input argument */
    let strReversed = ''

    /** Reversing the input argument */
    for(let i = str.length - 1; i >= 0; i--){
        strReversed += str[i]
    }

    /** Performing the check between the processed input string, and the processed reversed string */
    return removeNonAlphaNumericAndJoin(strReversed).toLowerCase() === removeNonAlphaNumericAndJoin(str).toLowerCase()
}


/** Testing a few inputs */
console.log(palindrome("never odd or even")) /** Returns true */
console.log(palindrome('once a rat now a cat')) /** Returns false */
                    

My Thought Process



Search And Replace

This is a program that takes a string (first argument), and replaces a word in the string (second argument), with another word (third argument) without using the String "replace()" method.

                        
function myReplacer(str, before, after) {
  /** Split the input string into an array of words */
  const strArray = str.split(" ")

  /** Initializing a regular expression */
  const regex = /[A-Z]/g

  /** Carrying out a set of operations if the first letter of the word to be replaced in upper case */
  if(regex.test(before[0]) === true){

    /** Finding the index of the word to be replaced */
    const replaceIndex = strArray.indexOf(before)

    /** Spreading the replacing word into an array of characters */
    let afterSpread = [...after]

    /** Converting the first letter of the replacing word to uppercase */
    afterSpread[0] = afterSpread[0].toUpperCase();

    /** Joining back the array of characters into a word */
    const joinedAfter = afterSpread.join("");

    /** Replacing the word to be replaced with the replacing word */
    strArray.splice(replaceIndex, 1, joinedAfter);

    /** Assembling the array of words back into a string */
    const joinedStr = strArray.join(" ");

    /** Returning the result */
    return joinedStr;
  }

  /** Carrying out a set of operations if the first letter of the word to be replaced in lower case */

  /** Finding the index of the word to be replaced */
  const replaceIndex = strArray.indexOf(before)

  /** Spreading the replacing word into an array of characters */
  let afterSpread = [...after]

  /** Converting the first letter of the replacing word to uppercase */
  afterSpread[0] = afterSpread[0].toLowerCase()

  /** Joining back the array of characters into a word */
  const joinedAfter = afterSpread.join("")

  /** Replacing the word to be replaced with the replacing word */
  strArray.splice(replaceIndex, 1, joinedAfter)

  /** Assembling the array of words back into a string */
  const joinedStr = strArray.join(" ")

  /** Returning the result */
  return joinedStr;
  
  }


  /** Calling the function with different string arguments */
  myReplacer("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
  myReplacer("He is Sleeping on the couch", "Sleeping", "sitting")
                    

My Thought Process



Roman Numeral Converter

This is a simple program that converts an Arabic numeral within the range of 1 to 3999, to a Roman Numeral

                        
function convertToRoman(num) {

  if(num >= 4000){
      return 'Input Above Range!'
  }
  
  let holder = '';
  let numVar = num;
  
  while(numVar >= 1000){
      holder += 'M';
      numVar -= 1000;
  }
  
  while(numVar >= 900){
      holder += 'CM';
      numVar -= 900;
  }
  
  while(numVar >= 500){
      holder += 'D';
      numVar -= 500;
  }
  
  while(numVar >= 400){
      holder += 'CD';
      numVar -= 400;
  }
  
  while(numVar >= 100){
      holder += 'C';
      numVar -= 100;
  }
  
  while(numVar >= 90){
      holder += 'XC';
      numVar -= 90;
  }
  
  while(numVar >= 50){
      holder += 'L';
      numVar -= 50;
  }
  
  while(numVar >= 40){
      holder += 'XL';
      numVar -= 40;
  }
  
  while(numVar >= 10){
      holder += 'X';
      numVar -= 10;
  }
  
  while(numVar == 9){
      holder += 'IX';
      numVar -= 9
  }
  
  while(numVar >= 5){
      holder += 'V';
      numVar -= 5;
  }
  
  while(numVar == 4){
      holder += "IV";
      numVar -= 4;
  }
  console.log(numVar)
  
  while(numVar >= 1){
      holder += "I";
      numVar -= 1;
  }
  
  console.log(holder)
  return holder;
}
    
convertToRoman(36);
convertToRoman(214);
                    

My Thought Process