Algorithms Flashcards
How do you combine two arrays with concat?
var oldArray = [1,2,3]; var newArray = [];
var concatMe = [4,5,6];
newArray = oldArray.concat(concatMe); //console.log(newArray); -> [1,2,3,4,5,6]
How do you flatten an array of arrays with reduce?
var flattened = [[0, 1], [2, 3], [4, 5]].reduce( function(a, b) { return a.concat(b); }, [] ); // flattened is [0, 1, 2, 3, 4, 5]
Write a function that gets the remainder of dividing two numbers together.
- Do NOT use the actual built-in modulo (aka “remainder”) operator (%) in your implementation.
- 0 % ANYNUMBER = 0.
- ANYNUMBER % 0 = NaN.
- If either operand is NaN, then the result is NaN.
- Modulo always returns the sign of the first number.
function modulo(num1, num2) { if(isNaN(num1) || isNaN(num2)){ return NaN; } if(num1 === 0){ return 0; } if(num2 === 0){ return NaN; }
var newNum1 = Math.abs(num1); var newNum2 = Math.abs(num2);
var quot = newNum1 - Math.floor( newNum1 / newNum2 ) * newNum2 ;
if(num1 < 0){ return -(quot); } else{ return quot; } } var output = modulo(25, 4); console.log(output); // --> 1
Write a function called “removeArrayValues”.
Given an object, “removeArrayValues” removes any properties whose values are arrays.
function removeArrayValues(obj) { // your code here var result = obj for (var prop in result){ if (result.hasOwnProperty(prop)){ if(result[prop].constructor === Array){ delete result[prop]; } } } return result; } var obj = { a: [1, 3, 4], b: 2, c: ['hi', 'there'] } removeArrayValues(obj); console.log(obj); // --> { b: 2 }
Write a function called “repeatString”.
Given a string and a number, “repeatString” returns the given string repeated the given number of times.
var output = repeatString('code', 3); console.log(output); // --> 'codecodecode'
function repeatString(string, num) { // your code here if (num ===0){ return ''; } else if(num === 1){ return string; }else{ return string+repeatString(string,num-1); } } var output = repeatString('code', 3); console.log(output); // --> 'codecodecode'
Write a function called “select”.
Given an array and an object, “select” returns a new object whose properties are those in the given object AND whose keys are present in the given array.
Notes:
- If keys are present in the given array, but are not in the given object, it should ignore them.
- It does not modify the passed in object.
function select(arr, obj) { // your code here //create an empty object //loop through each element in array //loop through each property name //compare the element with the property name //if property name and element are equal //store the property in a new object //return the new object var result = {}; for(var prop in obj){ for(var i = 0; i < arr.length; i++){ if (prop === arr[i]){ result[prop] = obj[prop]; } } } return result; }
var arr = ['a', 'c', 'e']; var obj = { a: 1, b: 2, c: 3, d: 4 }; var output = select(arr, obj); console.log(output); // --> { a: 1, c: 3 }
Add all the individual numbers of a big number. If it’s negative, count only the first number as a negative.
var output = sumDigits(1148); console.log(output); // --> 14
var output = sumDigits(-316); console.log(output); // --> 4
function sumDigits(num) { var strArr = Math.abs(num).toString().split(''); var result = strArr.map(function(el){ return Number(el); }) if(num < 0){ result[0] = -Math.abs(result[0]); } return result.reduce(function(a,b){ return a + b; });
} var output = sumDigits(1148); console.log(output); // --> 14
var output = sumDigits(-316); console.log(output); // --> 4
Given a string of even and odd numbers, find which is the sole even
number or the sole odd number.
The return value should be 1-indexed, not 0-indexed.
Examples :
detectOutlierValue(“2 4 7 8 10”); // => 3 - Third number is odd, while the rest of the numbers are even
detectOutlierValue(“1 10 1 1”); //=> 2 - Second number is even, while the rest of the numbers are odd
*/
//input: string => "2 4 7 8 10" //outup: 1-index (NOT 0 index) of the integer that is not like the rest =>3
function detectOutlierValue(str){ //create evens array var evens = []; //create odds array var odds = []; //var array split str into an array var array = str.split(' ').map(function(el){ return Number(el); }); //convert all the elements into Numbers //using the map method //loop for (var i = 0; i < array.length; i++){ //check if it's even or odd if(array[i] % 2 !== 0){ odds.push(array[i]); } if(array[i] % 2 === 0){ evens.push(array[i]); } //if it's even i want to store it into an array of all evens //if it's odd I want to store it into an array of all odds }
if(evens.length > odds.length){
return array.indexOf(odds[0])+1;
}
if(evens.length < odds.length){
return array.indexOf(evens[0])+1;
}
}
console. log(detectOutlierValue(“2 4 7 8 10”)); // => 3 - Third number is odd, while the rest of the numbers are even
console. log(detectOutlierValue(“1 10 1 1”)); //=> 2 - Second number is even, while the rest of the numbers are odd
/* Ceboyrz qrfpevcgvba (frr vafgehpgvbaf sbe ubj gb qr-boshfpngr).
You will be given an array that contains two strings. Your job is to
create a function that will take those two strings and transpose them,
so that the strings go from top to bottom instead of left to right.
e.g. transposeTwoStrings([‘Hello’,’World’]);
should return: H W e o l r l l o d */
//input: array //ouput: two strings verticale
function transposeTwoStrings(array){ //seperate the two element into their own variables //newArray1 = array[0] var newArray1 = array[0]; //newArray2 = array[1] var newArray2 = array[1]; //create a result array var result = [] for(var i = 0; i < newArray1.length; i++){ //loop //pair each array element at index i for both arrays //push the pairs into the storing array + \n var pair = newArray1[i] + ' ' + newArray2[i] + '\n'; result.push(pair); }
//return soring array return result.join(''); }
console.log(transposeTwoStrings([‘Hello’,’World’]));
Write a function ‘fromListToObject’ which takes in an array of arrays, and returns an object with each pair of elements in the array as a key-value pair.
Example input:
[[‘make’, ‘Ford’], [‘model’, ‘Mustang’], [‘year’, 1964]]
Function's return value (output): { make : 'Ford' model : 'Mustang', year : 1964 }
function fromListToObject(array) { //create object obj = {}; //loop through each subarray in the array for(var i = 0; i < array.length; i++){ //subarray[0] = key //subarray[1] = value obj[array[i][0]] = array[i][1]; }
//return obj return obj }
fromListToObject([[‘make’, ‘Ford’], [‘model’, ‘Mustang’], [‘year’, 1964]]
);
/* Ceboyrz qrfpevcgvba (qr-boshfpngr jvgu EBG-13 nf hfhny).
Given a list of non-negative integers and a target sum, find a pair of numbers that sums to the target sum.
Example:
var pair = findPairForSum([3, 34, 4, 12, 5, 2], 9); console.log(pair); // --> [4, 5] */ //input: array, targetSum //output: pair of array elements that add to the targetSum
function findPairForSum(array, targetSum){ //loop for(var i = 0; i [4, 5]
Using the JavaScript language, have the function ArithGeo(arr) take the array of numbers stored in arr and return the string “Arithmetic” if the sequence follows an arithmetic pattern or return “Geometric” if it follows a geometric pattern.
If the sequence doesn’t follow either pattern return -1.
An arithmetic sequence is one where the difference between each of the numbers is consistent, where as in a geometric sequence, each term after the first is multiplied by some constant or common ratio.
Arithmetic example: [2, 4, 6, 8] and Geometric example: [2, 6, 18, 54]. Negative numbers may be entered as parameters, 0 will not be entered, and no array will contain all the same elements.
function ArithGeo(arr) {
// this function will loop through the provided array // checking to see if the difference provided matches // every element-pair difference in the array function arrayDiffs(diff, arr, subtract) {
// loop starting from i=2 and check if every difference is the same for (var i = 2; i < arr.length; i++) {
// store the temporary difference var tempDiff = (subtract) ? arr[i] - arr[i-1] : arr[i] / arr[i-1];
// if differences do not match return false if (tempDiff !== diff) { return false; }
// if we reach the end of the array and all differences matched, return true else if (i === arr.length-1 && tempDiff === diff) { return true; }
}
}
// store the first difference for a potential arithmetic sequence var diffArith = arr[1] - arr[0];
// store the first difference for a potential geometric sequence var diffGeo = arr[1] / arr[0];
// check the whole array for an arithmetic sequence var isArithSeq = arrayDiffs(diffArith, arr, true);
// if not an arithmetic sequence, check for geometric sequence if (!isArithSeq) {
var isGeoSeq = arrayDiffs(diffGeo, arr, false); return (isGeoSeq) ? "Geometric" : -1;
} else {
return "Arithmetic";
}
}
ArithGeo([3, 9, 27, 81]);