FreeCodeCamp Algorithms Flashcards

1
Q

Write a function partlist that gives all the ways to divide a list (an array) of at least two elements into two non-empty parts.

Example:

a = [“az”, “toto”, “picaro”, “zone”, “kiwi”] –>

[[“az”, “toto picaro zone kiwi”], [“az toto”, “picaro zone kiwi”], [“az toto picaro”, “zone kiwi”], [“az toto picaro zone”, “kiwi”]]

A

a = [“I”, “wish”, “I”, “hadn’t”, “come”];

// [["az", "toto picaro zone kiwi"], ["az toto", "picaro zone kiwi"], 
//["az toto picaro", "zone kiwi"], ["az toto picaro zone", "kiwi"]]
function partlist(arr) {
//   var output = [];
//   for(var i =0; i < arr.length-1; i++){
//     var first = arr.slice(0,i+1).join(' ');
//     var second = arr.slice(i+1,arr.length).join(' ');
//     var loopArray = [first, second]; 
//     output.push(loopArray);  
//   }
  var output = arr.reduce(function(all, item, index){
    if(index < arr.length-1){
      var first = arr.slice(0,index+1).join(' ');
      var second = arr.slice(index+1,arr.length).join(' ');
      var loopArray = [first, second];
      all.push(loopArray); 
    }
return all;    },[]);

return output;

}
console.log(partlist(a));

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays.

A
function largestOfFour(arr) {
  //input: array of arrays
  //output: an array with the largest number in each array
  //loop through each element in the outer array
  //loop through element in each subarray
  //return the largest number in each subarray
  //add each largest number into a storing array
  //return the array with all the largest stored numbers
 return arr.reduce(function(all,item,index){
    var largestSubItem = item.reduce(function(subAll,subItem,subIndex){
      if(subItem > subAll){
        subAll = subItem; 
      }
      return subAll; 
    },0);
all.push(largestSubItem);
return all;    },[]);

}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Write a function that takes 2 inputs
str => string
target => string

check if str ends in the target string. This should account for single word strings and strings with sentences.

A
function confirmEnding(str, target) {
  //input:str => string, target => string => check if str ends in target
  //output: boolean => answers whether str ends in target
  //split the string into whole words array
  //get the last element of the words array
  //split the last word 
  var start = str.length - target.length;
  if(str.substring(start, str.length)===target){
    return true; 
  }else{
    return false; 
  }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

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.

For example, [“hello”, “Hello”], should return true because all of the letters in the second string are present in the first, ignoring case.

The arguments [“hello”, “hey”] should return false because the string “hello” does not contain a “y”.

Lastly, [“Alien”, “line”], should return true because all of the letters in “line” are present in “Alien”.

A
function mutation(arr) {
  //input: arr=> array with two strings
  //output: boolean => if all chars in second string are present in the first string
  var stringOneArr = arr[0].toLowerCase().split('');
  var stringTwoArr = arr[1].toLowerCase().split('');
  return stringTwoArr.reduce(function(all, item, index){
    if(stringOneArr.indexOf(item)===-1){
      return false;
    }
    return all;
  },true);
}

mutation([“hello”, “hey”]);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

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).

A
function getIndexToIns(arr, num) {
  // Find my place in this sorted array.
  //input: arr => array, num => integer
  //output: integer of index where num should be inserted
    //when arr is sorted in ascending order
  //arr to ascending order
  //check num against each array item
  //if greater than item
    //move on
  //if less than the item or equal
    //return index of the item
  //return the index where it should be inserted

return arr.sort(function(a,b){
return a - b;
}).reduce(function(all,item,index){

if(item-num<0){
  all = index+1; 
}
return all; 

},0);

//   for(var i = 0; i < sortArr.length; i++){
//     output = i;
//     if (num <= sortArr[i]){  
//       return output;
//     }
//   }
//   return output+1; 

}
getIndexToIns([10, 20, 30, 40, 50], 30);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

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.

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

All letters will be uppercase. Do not transform any non-alphabetic character (i.e. spaces, punctuation), but do pass them on.

A
function rot13(str) { // LBH QVQ VG!
  //65-90 capital letters
  //add 13 to element char code
    //if sum is greater than 90
      //subtract sum from 90
        //add the absolute value to 64
        //result becomes the char code
//   var output = ''; 
//   for(var i = 0; i < str.length; i++){
//     var charCode = str.charCodeAt(i);
//     if(charCode >= 65 &amp;&amp; charCode <=90){
//       charCode += 13;
//       if (charCode > 90){
//         charCode = Math.abs(90-charCode) + 64; 
//       }
//     }
//     output += String.fromCharCode(charCode);
//   }
//   return output;
 return str.split(' ').reduce(function(all,item,index){
   item = item.split('');
   var word = item.reduce(function(word, letter, index){
      var charCode = letter.charCodeAt(0); 
      if(charCode >=65 &amp;&amp; charCode <= 90){
        charCode+=13; 
        if(charCode > 90){
         charCode = Math.abs(90-charCode) + 64; 
        }
      }
      word += String.fromCharCode(charCode); 
      return word; 
   }, '');

all.push(word);

return all;

},[]).join(‘ ‘);
}

// Change the inputs below to test
rot13("SERR PBQR PNZC");
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

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.

A

function diffArray(arr1, arr2) {

return arr1.concat(arr2).filter(function(value, index, arr){
if(arr.slice(index+1, arr.length).indexOf(value) === -1 &&
arr.slice(0,index).indexOf(value)=== -1){
return value;
}
});

}

diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

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.

For example, if the first argument is [{ first: “Romeo”, last: “Montague” }, { first: “Mercutio”, last: null }, { first: “Tybalt”, last: “Capulet” }], and the second argument is { last: “Capulet” }, then you must return the third object from the array (the first argument), because it contains the property and its value, that was passed on as the second argument.

A
function whatIsInAName(collection, source) {
  // What's in a name?
//   var arr = [];
  // Only change code below this line
  //input: collection=> array of objects, source => object
  //ouput: objects that have the key value pairs of source in them
  //loop through collection array
  //compare key and value of source
  var sourceKeys = Object.keys(source);
//   for(var i =0; i < collection.length; i++){
//     var shouldPush=0; 
//     for(var j = 0; j< sourceKeys.length; j++){
//       if(collection[i][sourceKeys[j]] === source[sourceKeys[j]]){
//          shouldPush++; 
//       }
//     }
//     if(shouldPush===sourceKeys.length){
//       arr.push(collection[i]);
//     }

// }

return collection.filter(function(item, index, array){
return sourceKeys.every(function(key){
return item.hasOwnProperty(key) && item[key]===source[key];
});

});

  // Only change code above this line
//   return arr;
}

whatIsInAName([{ first: “Romeo”, last: “Montague” }, { first: “Mercutio”, last: null }, { first: “Tybalt”, last: “Capulet” }], { last: “Capulet” });

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Perform a search and replace on the sentence using the arguments provided and return the new sentence.

First argument is the sentence to perform the search and replace on.

Second argument is the word that you will be replacing (before).

Third argument is what you will be replacing the second argument with (after).

NOTE: Preserve the case of the original word when you are replacing it. For example if you mean to replace the word “Book” with the word “dog”, it should be replaced as “Dog”

A
function myReplace(str, before, after) {
  //input: str => string of characters,  before => word in str, after => word not in str
  //output: str with before replaced by after 
  if(before.charAt(0) === before.charAt(0).toUpperCase()){
    after = after.charAt(0).toUpperCase() + after.slice(1); 
  }

return str.replace(before, after);
}

myReplace(“He is Sleeping on the couch”, “Sleeping”, “sitting”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Pig Latin
Translate the provided string to pig latin.

Pig Latin takes the first consonant (or consonant cluster) of an English word, moves it to the end of the word and suffixes an “ay”.

If a word begins with a vowel you just add “way” to the end.

Input strings are guaranteed to be English words in all lowercase.

A

function translatePigLatin(str) {

  var vowel = ['a','e','i','o','u'], 
      firstLetter = str.charAt(0);
  function isVowel(char){
    return vowel.includes(char);
  }
  if(isVowel(firstLetter)){
    return str+'way';
  }else{
     for(var i = 0; i < str.length; i++){
      if(isVowel(str[i])){
        var consonantsCut = str.substr(0,i);
        return str.slice(i) + consonantsCut+'ay';
      }
    }
 }

}

translatePigLatin(“glove”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

DNA Pairing
The DNA strand is missing the pairing element. Take each character, get its pair, and return the results as a 2d array.

Base pairs are a pair of AT and CG. Match the missing element to the provided character.

Return the provided character as the first element in each array.

For example, for the input GCG, return [[“G”, “C”], [“C”,”G”],[“G”, “C”]]

The character and its pair are paired up in an array, and all the arrays are grouped into one encapsulating array.

A
function pairElement(str) {
   var pairs = {
     A: 'T',
     T: 'A',
     G: 'C',
     C: 'G',
   };
//    return str.split('').reduce(function(all, item, index){
//      var subArr = [];
//      subArr.push(item);
//      subArr.push(pairs[item]);
//      all.push(subArr);
//      return all; 
//    },[]);

return str.split(‘’).map(function(item){
return [item, pairs[item]];
});

}

pairElement(“ATCGA”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Missing letters
Find the missing letter in the passed letter range and return it.

If all letters are present in the range, return undefined.

fearNotLetter(“abce”) should return “d”.

A
function fearNotLetter(str) {
  //input: str => string of characters in order alphabetically
  //output: the letter missing from the sequence,
  //lopp through str
  //convert each letter to it's charcode
  //if letter before it is not 1 less than it 
    //then return the letter charcode 1 less than the current letter
  //if they are in order, then return undefined
    //ouput variable without defining it

// var result;

//   for(var i = 1; i 0){
      var charCode = str.charCodeAt(index),
          previous = str.charCodeAt(index - 1),
          shouldBe = charCode-1;
        if(charCode - previous !== 1){
          all = String.fromCharCode(shouldBe); 
        }
    }
    return all; 

},undefined);

}

console.log(fearNotLetter(“abcdf”));

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Sorted Union
Write a function that takes two or more arrays and returns a new array of unique values in the order of the original provided arrays.

In other words, all values present from all arrays should be included in their original order, but with no duplicates in the final array.

The unique numbers should be sorted by their original order, but the final array should not be sorted in numerical order.

uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]) should return [1, 3, 2, 5, 4].

A
function uniteUnique(arr) {
  //input: arr => multiple arrays
  //output: an array with all arrays joined together in order and with no duplicates
  //create an array out of the arguments
  //join the arrays into one array
  //remove any duplicates

var allArrs = Array.prototype.slice.call(arguments);

  return allArrs.reduce(function(all, item, index){
    item.forEach(function(element){
      if(all.indexOf(element) === -1){
        all.push(element); 
      }
    });
    return all;
  },[]);

}

uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Sorted Union
Write a function that takes two or more arrays and returns a new array of unique values in the order of the original provided arrays.

In other words, all values present from all arrays should be included in their original order, but with no duplicates in the final array.

The unique numbers should be sorted by their original order, but the final array should not be sorted in numerical order.

uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]) should return [1, 3, 2, 5, 4].

A
function uniteUnique(arr) {
  //input: arr => multiple arrays
  //output: an array with all arrays joined together in order and with no duplicates
  //create an array out of the arguments
  //join the arrays into one array
  //remove any duplicates

// var allArrs = Array.prototype.slice.call(arguments);

//   return allArrs.reduce(function(all, item, index){
//     item.forEach(function(element){
//       if(all.indexOf(element) === -1){
//         all.push(element); 
//       }
//     });
//     return all;
//   },[]);

// var args = Array.prototype.slice.call(arguments);

//   return args.reduce(function(all, item, index){
//     return all.concat(item);    
//   },[]).filter(function(item, index, array){
//     return array.indexOf(item) === index; 
//   });

var allArrs = Array.prototype.slice.call(arguments);

return allArrs.reduce(function(all, item){
return all.concat(item.filter(function(element){
return all.indexOf(element) < 0;
}));
});

}

uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Sum All Primes
Sum all the prime numbers up to and including the provided number.

A prime number is defined as a number greater than one and having only two divisors, one and itself. For example, 2 is a prime number because it’s only divisible by one and two.

The provided number may not be a prime.

A
function sumPrimes(num) {
  //input: num => number
  //output: the sum of all prime numbers leading up to and including num
  //loop through each number that leads to num\
  //test each number to see if it's prime
    //another for loop that checks every number below the number
      //call modulo on each sub number
      //if any of the numbers give you a 0 from the modulo operator
      //dont add this to the storing array
  //write how to find a prime number in the brain book
    //if its prime store it into an array
  //add up the elements in the stored array
  var primes = []; 
  function isPrime(int){
    if(int === 2){
      return true;
    }else{
      for(var j = 2; j < int; j++){
        if(int % j === 0){
          return false; 
        }
      }
      return true; 
    }
  }
  for(var i = 2; i <= num; i++){
    if(isPrime(i)===true){
      primes.push(i);
    }
  }

return primes.reduce(function(all, item, index){
return all + item;
},0);
}

sumPrimes(10);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Given a positive integer num, return the sum of all odd Fibonacci numbers that are less than or equal to num.

The first two numbers in the Fibonacci sequence are 1 and 1. Every additional number in the sequence is the sum of the two previous numbers. The first six numbers of the Fibonacci sequence are 1, 1, 2, 3, 5 and 8.

For example, sumFibs(10) should return 10 because all odd Fibonacci numbers less than 10 are 1, 1, 3, and 5.

A
// function sumFibs(num) {
  //input: num => integer
  //output: sum of all ODD fibonacci numbers below and equal to num
  //create an array output to store the odd fibs
  //create var to store the sum of fibs
  //while greatest fib in the array is less than or equal to num
    //sum += sum
    //if sum is odd then store in output
  //reduce output to the sum of it's elements
  //return the reduced output 
 //MY SOLUTION: 
//   var output = [], fibArr = [1,1], nextFib; 
//   function sumArray (arr){
//     return arr.reduce(function(all, item, index){
//      return all + item; 
//    }); 
//   }

// while(fibArr[0] <= num){

//    if (fibArr[0] % 2 !== 0){
//      output.push(fibArr[0]);
//    }
//    nextFib = sumArray(fibArr); 
//    fibArr.shift();
//    fibArr.push(nextFib);   
//   }
//   return sumArray(output); 
// }

//SEXY YOUTUBE SOLUTION:

Array.prototype.last = function(){
return this[this.length-1];
}

Array.prototype.secondToLast = function(){
return this[this.length-2];
}

function sumFibs(num){
  var sequence = [1,1];

while(sequence.secondToLast() + sequence.last() <= num){
sequence.push(sequence.secondToLast() + sequence.last());
}

  return sequence.filter(function(num){
    return num % 2 !== 0;
  }).reduce(function(a,b){
    return a + b; 
  });
}

console.log(sumFibs(10));

17
Q

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).

findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; }) should return 8.

A

function findElement(arr, func) {

return arr.filter(func)[0];
}

findElement([1, 2, 3, 4], function(num){ return num % 2 === 0; });

18
Q

Drop it
Drop the elements of an array (first argument), starting from the front, until the predicate (second argument) returns true.

The second argument, func, is a function you’ll use to test the first elements of the array to decide if you should drop it or not.

Return the rest of the array, otherwise return an empty array.

A

function dropElements(arr, func) {

while(!func(arr[0])){
arr.shift();
}

return arr;
}

dropElements([1, 2, 3, 4], function(n) {return n >= 3;});

19
Q

Binary Agents
Return an English translated sentence of the passed binary string.

The binary string will be space separated.

binaryAgent(“01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111”) should return “Aren’t bonfires fun!?”

A

function binaryAgent(str) {

  //loop through each element and call the below line of code on it
  //add that letter to an aray
  //once loop through all, join them together at ,
  return str.split(' ').reduce(function(all, item, index){
    all+= String.fromCharCode(parseInt(item, 2));
    return all; 
  },''); 

}

binaryAgent(“01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111”);

20
Q

Everything Be True
Check if the predicate (second argument) is truthy on all elements of a collection (first argument).

Remember, you can access object properties through either dot notation or [] notation.

Solve this 3 ways:
for loop
reduce
every

truthCheck([{“user”: “Tinky-Winky”, “sex”: “male”}, {“user”: “Dipsy”}, {“user”: “Laa-Laa”, “sex”: “female”}, {“user”: “Po”, “sex”: “female”}], “sex”) should return false

A
function truthCheck(collection, pre) {
  // Is everyone being true?
  //input: collection=> array of objects, pre=>string
  //ouput: boolean, check if pre is a key in every element that has a boolean of true
  //loop through collection
  //call collection.pre
    //check the value with Boolean() 
    //if false
    //return false
    //if no false
    //return true
  //for loop
//   for(var i =0; i < collection.length; i++){
//     if(!collection[i][pre]){
//       return false; 
//     }
//   }
//   return true;

//reduce loop

//     return collection.reduce(function(all, item, index){
//     if (all===false){
//       all = false;
//     }
//     if(!item[pre]){
//       all = false; 
//     }
//     return all; 
//   },true);

//every loop

return collection.every(function(element, index, array){
return element[pre];
});

}

truthCheck([{“user”: “Tinky-Winky”, “sex”: “male”}, {“user”: “Dipsy”, “sex”: “male”}, {“user”: “Laa-Laa”, “sex”: “female”}, {“user”: “Po”, “sex”: “female”}], “sex”);

21
Q

Arguments Optional
Create a function that sums two arguments together. If only one argument is provided, then return a function that expects one argument and returns the sum.

For example, addTogether(2, 3) should return 5, and addTogether(2) should return a function.

Calling this returned function with a single argument will then return the sum:

var sumTwoAnd = addTogether(2);

sumTwoAnd(3) returns 5.

If either argument isn’t a valid number, return undefined.

A
function addTogether() {
  //input => happy=> 2 numbers
        //=> sad1=> 1 number
        //=> sad2=> something that is not a number
  //outupt => happy=> sum of two numbers
          //=>sad1=> function that takes an input to sum the orignial                          number that was passed
          //=>sad2=> undefined
  //check if the arguments are both numbers
    //if they are not
      //return undefined
  //if they are both numbers
    //sum them together
  //if only one input in the arguments and is a number
    //store this number in a variable to be used in the inner function
  //create a function inside our function
    //this function adds two numbers that were inputed
 var args = Array.prototype.slice.call(arguments);
 var oneNum = args[0];
  function validNumber(arr){
   return arr.every(function(item){
     return typeof item === 'number';
   });
  }
  function sumEm(input){
    if(typeof input !== 'number'){
      return undefined; 
    }else{
      return oneNum + input; 
    }

}

if (!validNumber(args)){
return undefined;
}

 if(args.length > 1){
   return sumEm(args[1]);
 }else{
   return sumEm; 
 }

}

addTogether(2)([3]);