FreeCodeCamp Algorithms Flashcards
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 = [“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));
Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays.
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]]);
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.
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; } }
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”.
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”]);
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).
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);
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.
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 && 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 && 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");
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.
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]);
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.
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” });
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”
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”);
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.
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”);
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.
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”);
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”.
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”));
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].
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]);
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].
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]);
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.
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);