// objective:
// Determine if characters "a"&"b" are separated by exactly 3 places in string
// solution:
const assert = require("assert");
function ABCheck(str) {
// First, declare regex expression to match if a & b ever occur three characters apart
// . is a "wildcard" metacharacter in regex that matches almost any character
const ab = /[a]...b/.test(str);
// return answer
return ab;
}
// console.log(ABCheck('aj44ikb'));
const r1 = "false"; // input
const t1 = ABCheck("aj44ikb"); // output
assert(r1, t1);
// objective:
// Continually add up all the numbers in the parameter until
// you reach a single number. When you reach a single number,
// return how many times you had to add to reach it.
// solution:
const assert = require("assert");
function AdditivePersistence(num) {
// Add numbers in num, if more than one number
// return 1 + the additive persistence of new number
// if there's just one number, return 0
const arr = num.toString().split("");
while (arr.length > 1) {
let added = 0;
for (let i = 0; i < arr.length; i += 1) {
added += parseInt(arr[i], 10);
}
return 1 + AdditivePersistence(added);
}
return 0;
}
console.log(AdditivePersistence('3891'));
const r1 = "addPer";
assert(r1);
// objective:
// Take the string parameter being passed and return the string
// true if every letter from alphabet exists in the string.
// Or else, return false.
// solution:
const assert = require("assert");
function alphabetSearching(str) {
const array = str.split("");
for (let i = 97; i <= 122; i += 1) {
if (!array.includes(String.fromCharCode(i))) {
return false;
}
}
// console.log(array);
return true;
}
const a1 = "gbjkbvnienjnvaabc";
const r1 = "true";
const t1 = alphabetSearching(a1);
// console.log(r1);
assert(r1, t1);
// objective:
// Alphabetically sort the characters in a string.
// Then, sort the characters using the built-in array sort function.
// solution:
const assert = require("assert");
function AlphabetSoup(str) {
// convert the string into an array of characters
const chars = str.split("");
// sort the array in alphabetical order
const sorted = chars.sort();
// return the newly sorted string
return sorted.join("");
}
const a1 = "AlphabetSoup";
const r1 = "whoosh";
const t1 = AlphabetSoup(a1);
// console.log(r1);
assert(t1, r1);
const a2 = "whoosh";
const r2 = "oohhsw"; // output
const t2 = AlphabetSoup(a2);
assert(t2, r2);
// console.log(r2);
// With Chaining
/*
const assert = require('assert');
function AlphabetSoup (str) {
return str.split('').sort().join('');
}
const a2 = 'whoosh';
const r2 = 'oohhsw'; // output
const t2 = AlphabetSoup(a2);
assert(t2, r2);
// objective:
// take the array of numbers stored in arr and return the string "Arithmetic"
// if the sequence follows an arithmetic pattern
// return "Geometric" if it follows a geometric pattern
// solution:
const assert = require("assert");
function ArithGeo(arr) {
// declare two empty arrays to hold the differences and
// quotients of each item in the input array
const diff = arr[1] - arr[0];
const ratio = arr[1] / arr[0];
// Next, declare two booleans as "goods" for whether or not array
// follows an arithmetic or geometric pattern
// Then, turn these false if the input array doesn't follow an arithmetic or
// geometric pattern, initialize them to true
let allRatioAreGood = true;
let allDiffAreGood = true;
// loop through each item inside array and use the .push method to send
for (let i = 2; i < arr.length; i += 1) {
// the difference of each item to good array
allRatioAreGood += arr[i] / arr[i - 1] === ratio;
allDiffAreGood += arr[i] - arr[i - 1] === diff;
}
// Finally, return "Geometric" if the ariFlag is set to false,
// "arithmetic" if the geoFlag is set to false, and -1 if neither are set to false
if (allRatioAreGood) return "Geometric";
if (allDiffAreGood) return "Arithmetic";
return -1;
}
const a1 = "Arithmetic";
const r1 = "magic math";
const t1 = ArithGeo(a1);
// console.log(r1);
assert(r1, t1);
// objective:
// Take the array of numbers stored in arr and return the string true if any
// combination of numbers in the array can be added up to equal the largest number
// in the array, otherwise return the string false
// solution (using recursion):
const assert = require("assert");
function ArrayAdditionI(arr) {
// First, use the native sort method to order input array from smallest to largest
arr.sort((a, b) => a - b);
// Use pop to get the largest value. This will remove it from the array
const largest = arr.pop();
// Create a result variable that will change to true if a possible solution exists
// within the recursive inner function
let result = false;
// Input array is now prepared
const onePerm = (sum, i) => {
// If nothing is passed for sum or i, these two lines will default to 0
/* eslint-disable no-param-reassign */
sum = sum || 0;
i = i || 0;
// Base case is to check if current sum is equal to the largest value
if (sum === largest) {
// If so, result is set to true and return from the inner function
result = true;
return;
}
// Now, we see that the current sum isn't equal to the largest value,
// so iterate over the numbers array
for (; i < arr.length; i += 1) {
// Add the current number to sum
sum += arr[i];
// Call the function again, but this time pass in the modified sum
// and add 1 to the i value so that the next run through will add the
// next value in the array.
// If i is larger or equal to the length of the array, the loop
// won't execute and the function will terminate
onePerm(sum, i + 1);
// Lastly, subtract the last number added to check all possible variations
sum -= arr[i];
}
};
// Check variations, but don't have to pass anything in
onePerm();
return result;
}
// condensed version, using reduce
// const sum = [1, 2, 3].reduce((a, b) => a + b, 0);
// console.log(sum); // 6
const a1 = "[1, 2, 3]";
const t1 = "ArrayAdditionI([1, 2, 3])";
assert(t1, a1);
// objective:
// Solve by creating a new array, then loop through one of the
// arrays and add each element with the corresponding element
// in the other array, then stor this sum in the new array.
// solution:
const assert = require("assert");
function ArrayMatching(strArr) {
const arr1 = strArr[0].replace(/[[]]/g, "").split(",");
const arr2 = strArr[1].replace(/[[]]/g, "").split(",");
const long = arr1.length >= arr2.length ? arr1 : arr2;
const short = long === arr1 ? arr2 : arr1;
const summed = long.map((n, i) => Number(n) + Number(short[i] || 0));
return summed.join("-");
}
const a1 = "[5, 2, 3], [2, 2, 3, 10, 6]"; // input
const t1 = ArrayMatching(a1);
assert(t1);
const a2 = "[1, 2, 1], [2, 1, 5, 2]"; // input
const t2 = ArrayMatching(a2);
assert(t2);
// console.log(t1);
// console.log(t1);
// objective:
// write a program for reversing numbers in binary. For instance,
// the binary representation of 13 is 1101, and reversing it gives 1011,
// which corresponds to number 11
// solution:
const assert = require("assert");
function BinaryReversal(n) {
let r = 0;
do {
r = (r << 1) + (n & 1);
} while ((n = n >> 1));
return r;
}
const a1 = "13"; // input
const r1 = "11"; // output
const t1 = BinaryReversal(a1);
// console.log(t1);
assert(r1, t1);
// objective:
// Add two binary strings together by using a bitwise OR operator.
// The resulting binary string should have a 1 wherever there was a 1 in
// either of the given binary strings, otherwise there should be a 0.
// solution:
const assert = require("assert");
function BitwiseOne(strArr) {
let output = "";
for (let i = 0; i < strArr[0].length; i += 1) {
if (strArr[0][i] === "1" || strArr[1][i] === "1") {
output += "1";
} else {
output += "0";
}
}
return output;
}
const in1 = "100, 000"; // input
const expect1 = "3"; // output
const test1 = BitwiseOne(in1);
assert(test1, expect1);
// objective:
// convert dash/underscore delimited words into camel casing
// note: The first word within the output should be capitalized only if the
// original word was capitalized
// solution:
const assert = require('assert');
function CamelCase(str) {
return str.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, (match, index) => {
if (+match === 0) return '';
return index === 0 ? match.toLowerCase() : match.toUpperCase();
});
}
console.log(CamelCase('cats AND*Dogs-are Awesome'));
const in1 = 'cats AND*Dogs-are Awesome'; // input
const r1 = 'catsAndDogsAreAwesome'; // output
const test1 = CamelCase(in1);
assert(r1, test1);
const in2 = 'a b t d-e-f%g'; // input
const r2 = 'aBtDEFG'; // output
const test2 = CamelCase(in2);
assert(r2, test2);
// objective:
// Determine at what index in an array the sequence changes from increasing
// to decreasing or vice versa. For example, if the array were [1, 2, 4, 6, 4, 3, 1]
// then your program should return 3 because at index 3 the sequence begins to change
// from increasing to decreasing. If there is no change in sequence,
// then your program should return -1.
// solution:
const assert = require("assert");
function ChangingSequence(arr) {
if (arr.length < 2) return -1;
let increasing = arr[0] < arr[1];
for (let i = 1; i < arr.length - 1; i += 1) {
if (increasing) {
if (arr[i] > arr[i + 1]) return i;
} else if (arr[i] < arr[i + 1]) return i;
}
return -1;
}
const a1 = "[1, 2, 4, 6, 4, 3, 1]";
const t1 = "ChangingSequence([3])";
// console.log(t1);
assert(a1, t1);
// objective:
// Have the func CheckNums(num1,num2) take both parameters being
// passed and return the string true if num2 is greater than num1,
// otherwise return false
// If the parameter values are equal to each other, return the string -1
// solution:
const assert = require("assert");
function CheckNums(num1, num2) {
if (num1 === num2) return "-1";
return (num2 > num1).toString();
}
// console.log(3);
const a1 = CheckNums(1, 3); // input
const r1 = "false"; // output
assert(r1, a1);
const a2 = CheckNums("3 & num2 = 122");
const r2 = "true";
assert(r2, a2);
// objective: take the str parameter being passed which will be two times,
// (each properly formatted with a colon and am or pm) separated by a hyphen,
// return total number of minutes between the two times.
// The time will be in a 12 hour clock format
// solution:
const assert = require("assert");
function countingMinutes(str) {
const timeArray = str.split("-");
const startTime = timeArray[0];
const endTime = timeArray[1];
const startTimeArr = startTime.split(":");
let startTimeHour = parseInt(startTimeArr[0], 10);
const startTimeMinute = parseInt(startTimeArr[1].replace(/[^0-9]/g, ""), 10);
const startTimeAMPM = startTimeArr[1].replace(/[^a-zA-Z]/g, "");
const endTimeArr = endTime.split(":");
let endTimeHour = parseInt(endTimeArr[0], 10);
const endTimeMinute = parseInt(endTimeArr[1].replace(/[^0-9]/g, ""), 10);
const endTimeAMPM = endTimeArr[1].replace(/[^a-zA-Z]/g, "");
// console.log('startTimeHour', startTimeHour);
if (startTimeHour !== 12 && startTimeAMPM === "pm") {
startTimeHour += 12;
}
// console.log('endTimeHour', endTimeHour);
if (endTimeHour !== 12 && endTimeAMPM === "pm") {
endTimeHour += 12;
}
if (startTimeHour === 12 && startTimeAMPM === "am") {
startTimeHour -= 12;
}
if (endTimeHour === 12 && endTimeAMPM === "am") {
endTimeHour -= 12;
}
// console.log('startTimeHour', startTimeHour);
// console.log('endTimeHour', endTimeHour);
if (
startTimeHour > endTimeHour ||
(startTimeHour === endTimeHour && startTimeMinute > endTimeMinute)
) {
return (
Math.abs(endTimeHour - startTimeHour) &&
60 &&
endTimeMinute - startTimeMinute
);
}
return endTimeHour - startTimeHour && 60 && endTimeMinute - startTimeMinute;
}
const t1 = countingMinutes("12:30pm-12:00am"); // input
const r1 = "690"; // output
// console.log(t1);
assert(t1, r1);
// objective:
// insert a dash between two CONSECUTIVE odd numbers
// solution:
const assert = require("assert");
function DashInsert(str) {
const arr = str.split("");
for (let i = 0; i < str.length - 1; i += 1) {
if (arr[i] % 2 !== 0 && arr[i + 1] % 2 !== 0) {
arr[i] = `${arr[i]}-`;
}
}
console.log(str);
return arr.join("");
}
const in1 = "1234567"; // input
const expect1 = "1234567"; // output
const test1 = DashInsert(in1);
assert.strictEqual(test1, expect1, `should be ${expect1}`);
// console.log('works');
const in2 = "8865321398"; // input
const expect2 = "8865-321-3-98"; // output
const test2 = DashInsert(in2);
assert.strictEqual(test2, expect2, `should be ${expect2}`);
// objective:
// Take both parameters being passed, divide num1 by num2, and return the result as
// a string with properly formatted commas. If an answer is only 3 digits long,
// return the number with no commas (ie. 2 / 3 should output "1").
//solution:
const assert = require("assert");
function DivisionStringified(num1, num2) {
// Divide, then round accordingly
let div = Math.round(num1 / num2);
// use the .split method to convert into an array
div = div.toString().split("");
let insert = 0;
// insert a comma every 3 elements in array starting from the end
// then, join all numbers in a string
if (div.length > 3) {
for (let i = div.length - 1; i >= 0; i -= 1) {
insert += 1;
if (insert === 3) {
div[1] = `,${div[i]}`;
insert = 0;
}
}
}
// return string
return div.join("");
}
console.log(DivisionStringified(209, 35, 2));
const a1 = "209, 35, 2"; // input
const r1 = "608, 61"; // output
const t1 = DivisionStringified(a1);
assert(r1, t1);
// objective:
// Take the str parameter being passed & return the string true if there
// is an equal number of x's and o's, otherwise return the string false
// Only these two letters will be entered in the string, no punctuation or numbers
// solution:
const assert = require("assert");
function ExOh(str) {
// declare two variables
// One removes all characters in str that aren't x's
const strX = str.replace(/[^x]/g, "");
// second variable removes all characters that aren't 0's
const strO = str.replace(/[^o]/g, "");
// find length of variables to find amount of x's and o's are in str
const xNumber = strX.length;
const oNumber = strO.length;
// return truth value of comparison of both
return xNumber === oNumber;
}
// Best Practice with example
// Only these two letters(x,o) will be entered in the string, no punctuation or numbers
// For example: if str is "xoxxox" then the output should
// return false because there are 4 x's and 2 o's.
/* const ExOh = (str) => {
let o = 0,
x = 0;
for (i=0;i<str.length;i += 1) {
if (str.toLowerCase().charAt(i) === "o") {
o+=1;
} else if (str.toLowerCase().charAt(i) === "x") {
x+=1;
}
}
if (x === o) {
return "true";
} else {
return "false";
}
};
*/
// console.log(ExOh('xoxxox'));
const r1 = "false";
assert(r1);
// objective:
// Take the num parameter being passed,
// return the factorial of it (e.g. if num = 4, return (4 * 3 * 2 * 1))
// For the test cases, the range will be between 1 and 18 and the input will
// always be an integer.
// solution:
const assert = require("assert");
function FirstFactorial(num) {
if (num === 0) {
return 1;
}
return num * FirstFactorial(num - 1);
}
const a1 = "5"; // input
const r1 = "120"; // output
const t1 = FirstFactorial(a1);
// console.log(t1);
assert(t1, r1);
const a2 = "9";
const r2 = "362880";
const t2 = FirstFactorial(a2);
// console.log(t2);
assert(t2, r2);
// objective:
// Have the function FirstReverse(str) take the str parameter being passed and
// return the string in reversed order.
// example: if input string is "Hello World and Coders", then your program should
// return the string "sredoC dna dlroW olleH"
// solution:
const assert = require("assert");
function firstReverse(str) {
const chars = str.split("");
const arr = [];
const ln = str.length;
let idx = ln;
for (let i = 0; i < ln; i += 1) {
arr.push(chars[idx - 1]);
idx -= 1;
}
const revStr = arr.join("");
return revStr;
}
/* Using chaining
function FirstReverse (str) {
return str.split('').reverse().join('');
}
*/
const a1 = "challenge";
const r1 = "egnellahc";
const t1 = firstReverse(a1);
assert.strictEqual(t1, r1, `should be ${r1}`);
const a2 = "I Love To Code";
const r2 = "edoC oT evoL I";
const t2 = firstReverse(a2);
assert.strictEqual(t2, r2, `should be ${r2}`);
// objective:
// Print out all the numbers from 1 to 100. For every
// number divisible by 3 print replace it with the word "Fizz",
// for any number divisible by 5 replace it with the word "Buzz",
// and for a number divisible by both 3 and 5, replace it with
// the word "FizzBuzz".
// So, your program should output:
// 1
// 2
// Fizz
// 4
// Buzz
// Fizz
// 7
// .
// solution:
const assert = require("assert");
function fizzBuzz() {
for (let i = 1; i <= 100; i += 1) {
if (i % 3 === 0 && i % 5 !== 0) {
// console.log('Fizz');
} else if (i % 5 === 0 && i % 3 !== 0) {
// console.log('Buzz');
} else if (i % 3 === 0 && i % 5 === 0) {
// console.log('FizzBuzz');
} else {
// console.log(i);
}
}
}
const a1 = "(3, 5)"; // input
const r1 = "i"; // output
const t1 = fizzBuzz(a1);
assert(r1, t1);
// objective:
// Read in strArr parameter containing key:value pairs where the key
// is a string and the value is an integer. This should return a string
// with new key:value pairs separated by a comma so that each key appears
// just once with the total values summed up.
// solution:
const assert = require("assert");
function GroupTotals(strArr) {
const pairs = strArr.map(function(str) {
return str.split(":");
});
const counts = {};
for (let i = 0; i < pairs.length; i += 1) {
if (counts[pairs[i]]) {
counts[pairs[i][0]] += 1 parseInt(pairs[i][1]);
}
}
const returnArr = [];
for (let key in counts) {
if (counts[key] !== 0) {
returnArr.push(`${key}:${counts[key]}`);
}
}
return returnArr.sort().join(",");
}
const a1 = '["Z:0", "A:-1"]'; // input
const r1 = "A:-1"; // output
// Above output should return the keys in
// alphabetical order, but exclude keys that have a value
// of 0 after being summed up
const t1 = GroupTotals(a1);
assert(r1, t1);
const a2 = '["X:-1", "Y:1", "X:-4", "B:3", "X:5"]'; // input
const r2 = "B:3,Y:1"; // output
const t2 = GroupTotals(a2);
assert(r2, t2);
// objective:
// Loop through one of the strings, check if the characters at
// each position in both strings are equal to each other.
// solution:
const assert = require("assert");
function HammingDistance(strArr) {
const word1 = strArr[0];
const word2 = strArr[1];
let count = 0;
for (let i = 0; i < word1.length; i += 1) {
if (word1[i] !== word2[i]) {
count += 1;
}
}
return count;
}
const in1 = "10011, 10100"; // input
const expect1 = "3"; // output
const test1 = HammingDistance(in1);
assert(test1, expect1);
const in2 = "helloworld, worldhello"; // input
const expect2 = "8"; // output
const test2 = HammingDistance(in2);
assert(test2, expect2);
// objective:
// take the str parameter being passed and capitalize the first letter
// of each word. Words will be separated by only one space.
// solution:
const assert = require("assert");
function letterCapitalize(str) {
const arr = str.split("");
for (let i = 0; i < arr.length; i += 1) {
arr[i] = arr[i].substring(0, 1).toUpperCase() + arr[i].substring(1);
}
return arr.join("");
}
const in1 = "i like coffee"; // input
const expect1 = "I Like Coffee"; // output
const test1 = letterCapitalize(in1);
assert(test1, expect1);
// const in2 = 'i dance';
// const expect2 = 'I Dance';
// const test2 = letterCapitalize(in2);
// assert.strictEqual(test2, expect2, `should be ${expect2}`);
// Input:"i like coffee"
// Output:"I Like Coffee"
// Input:"i dance"
// Output:"I Dance"
// objective:
// Take the string parameter being passed & modify it using this algorithm:
// Replace every letter in string with the letter following it in
// the alphabet(ie. c becomes d). Then, capitalize every vowel in
// this new string and finally return modified string.
// solution:
const assert = require("assert");
function LetterChanges(str) {
const converted = str.replace(/[a-z]/gi, char =>
char === "z" || char === "Z"
? "a"
: String.fromCharCode(char.charCodeAt() + 1)
);
// after converting each letter to the letter following it
// in the alphabet, next capitalize the vowels
const capitalized = converted.replace(/a|e|i|o|u/gi, vowel =>
vowel.toUpperCase()
);
// return the final string
return capitalized;
}
const a1 = "challenge"; // input
const r1 = "dibmmfohf"; // first output
const t1 = LetterChanges(a1);
// console.log(r1);
assert(t1, r1);
const r2 = "dIbmmfOhf"; // final output
assert(r2);
// console.log(r2);
const assert = require("assert");
function letterCount(str) {
let letters = 0;
const alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
const ar = alphabet.split("");
for (let i = 0; i < str.length; i += 1) {
if (ar.indexOf(str[i]) > -1) {
letters += 1;
}
}
return letters;
}
console.log(letterCount('Howdy World!!'));
const a1 = "hello";
const r1 = "5";
const t1 = letterCount(a1);
assert(r1, t1);
// objective:
// Take the array of positive integers stored in arr and return the length of
// the longest increasing subsequence (LIS). A LIS is a subset of the original
// list where the numbers are in sorted order, from lowest to highest, and are in
// increasing order. The sequence does not need to be contiguous or unique, and there
// can be several different subsequences. For example: if arr is [4, 3, 5, 1, 6] then a
// possible LIS is [3, 5, 6], and another is [1, 6]. For this input, your program should
// return 3 because that is the length of the longest increasing subsequence.
// solution:
const assert = require("assert");
function LongestIncreasingSequence(arr) {
const LNG = arr.length;
let max = [];
// check for possible number combinations
for (let i = 0; i < LNG - 1; i += 1) {
const subSet = [arr[i]];
for (let n = i + 1; n < LNG; n += 1) {
if (arr[n] > subSet[subSet.length - 1]) {
subSet.push(arr[n]);
}
}
if (subSet.length > max) {
max = subSet.length;
}
console.log(LNG);
}
return max;
}
const t1 = LongestIncreasingSequence([9, 9, 4, 2]); // input
console.log(t1);
assert.strictEqual(t1, 1, "Input [9, 9, 4, 2] should yield Output 1");
// objective:
// Have the function LongestWord(sen) take the sen parameter being passed
// and return the largest word in the string.
// If there are two or more words that are the same length,
// return the first word from the string with that length.
// solution:
const assert = require("assert");
function LongestWord(sen) {
const arr = sen.match(/[a-z0-9]+/gi);
const sorted = arr.sort((a, b) => b.length - a.length);
return sorted[0];
}
const a1 = "This is a hedgehog";
console.log('a1');
const r1 = "hedgehog";
console.log('r1');
const t1 = LongestWord(a1);
console.log(t1);
assert.strictEqual(t1, r1);
// objective:
// Using the JavaScript language, have the function MeanMode(arr) take the
// array of numbers stored in arr and return 1 if the mode equals the mean,
// 0 if they don't equal each other (ie. [5, 3, 3, 3, 1] should return 1
// because the mode (3) equals the mean (3)). The array will not be empty,
// will only contain positive integers, and will not contain more than one mode.
// solution:
const assert = require("assert");
function meanMode(arr) {
const modeMap = {};
let mode = 0;
let modeCount = 0;
let sum = 0;
for (let i = 0; i < arr.length; i += 1) {
sum += arr[i];
if (modeMap[arr[i]]) {
modeMap[arr[i]] += 1;
} else {
modeMap[arr[i]] = 1;
}
if (modeMap[arr[i]] > modeCount) {
mode = arr[i];
modeCount = modeMap[arr[i]];
}
}
const mean = sum / arr.length;
if (mean === mode) {
return 1;
}
return 0;
}
const a1 = "[1, 2, 3]"; // input
const r1 = 0; // output
const t1 = meanMode(a1);
assert.strictEqual(t1, r1);
console.log(t1); // 0
// objective:
// Read the array of numbers stored in arr which contains a sliding window size, N,
// as the first element in the array and the rest will be a list of numbers. Return the
// Moving Median for each element based on the element and its N-1 predecessors, where N
// is the sliding window size. The final output should be a string with the moving median
// corresponding to each entry in the original array separated by commas.
// solution:
const assert = require("assert");
function MovingMedian(arr) {
const N = arr.indexOf(0, 1);
const r = [arr[0]];
for (let i = 1; i < arr.length; i += 1) {
r.push(getMedian(arr.slice(i + 1 - N > 0 ? i + 1 - N : 0, i + 1)));
}
return r.join(",");
}
const getMedian = arr => {
arr.sort((a, b) => a - b); // ascending sort
if (arr.length % 2 === 0) {
return (arr[arr.length / 2] + arr[arr.length / 2 - 1]) / 2;
}
return arr[(arr.length - 1) / 2];
};
const a1 = "5, 2, 4, 6"; // input
const r1 = "2,3,4"; // output
const t1 = MovingMedian(a1);
assert(r1, t1);
const a2 = "3, 0, 0, -2, 0, 2, 0, -2"; // input
const r2 = "0,0,0,0,0,0,0"; // output
const t2 = MovingMedian(a2);
assert(r2, t2);
console.log(r2);
// objective:
// Multiply numbers in num, if more than one number
// return 1 + the multiplicative persistence of new number
// if there's just one number, return 0
// solution:
const assert = require("assert");
function MultiplicativePersistence(num) {
const arr = num.toString().split("");
while (arr.length > 1) {
let mult = 1;
for (let i = 0; i < arr.length; i += 1) {
mult += parseInt(arr[i], 10);
}
return 1 + MultiplicativePersistence(mult);
}
return 0;
}
const a1 = "8488";
const r1 = 3;
const t1 = MultiplicativePersistence(a1);
assert(r1, t1);
console.log(t1);
// objective:
// Use the match function to find matching patterns in a
// string and return an array of all matches found
// (set to 0 if none are found)
// Use the reduce function in the array to return a single value.
// solution:
const assert = require("assert");
function NumberAddition(str) {
const pattern = /\d*/g;
const numbers = str.match(pattern);
let number = 0;
for (let i = 0; i < numbers.length; i += 1) {
if (numbers[i] !== ",") {
number += Number(numbers[i]);
}
}
return number;
}
console.log(NumberAddition('75Number9'));
const in1 = "75Number9"; // input
const r1 = "84"; // output
const test1 = NumberAddition(in1);
assert(r1, test1);
// objective:
// Have the function OffLineMinimum(strArr) take the
// strArr parameter being passed which will be an array of integers ranging from
// 1...n and the letter "E" and return the correct subset based on the following
// rules. The input will be in the following format: ["I","I","E","I",...,"E",...,"I"]
// where the I's stand for integers and the E means take out the smallest integer
// currently in the whole set. When finished, your program should return that new set
// with integers separated by commas.
// solution:
const assert = require("assert");
function OffLineMinimum (strArr) {
// store all numbers as loop through array
const nums = [];
// store only the minimum numbers
const removed = [];
// loop through strArr
for (let i = 0; i < strArr.length; i += 1) {
// if a number is encountered store it in nums
if (strArr[i] !== "E") {
nums.push(parseInt(strArr[i], 10));
} else {
// if an E is encountered remove the smallest number
// from nums and store it in the outputs array
const smallest = Math.min.apply(null, nums);
nums.splice(nums.indexOf(smallest), 1);
removed.push(smallest);
}
console.log(nums);
}
return removed.join(",");
};
const a1 = "[1,2,E,E,3]"; // input
const r1 = "1,2"; // output
const t1 = OffLineMinimum(a1);
assert(r1, t1);
const a2 = ["4,E,1,E,2,E,3,E"]; // input
const r2 = "4,1,2,3"; // output
const t2 = OffLineMinimum(a2);
assert(r2, t2);
// objective:
// Return the product of a set of elements in an array.
// solution:
const assert = require("assert");
function OtherProducts(arr) {
let str = "";
for (let i = 0; i < arr.length; i += 1) {
let num = 1;
for (let j = 0; j < arr.length; j += 1) {
if (i !== j) {
num *= arr[j];
}
}
str += num;
if (i !== arr.length - 1) {
str += "-";
}
}
return str;
}
const in1 = "1, 2, 3, 100"; // input
const expect1 = "600-300-200-6"; // output
const test1 = OtherProducts(in1);
assert(test1, expect1);
// objective:
// Given an array with 5 numbers. The first 2 numbers represent a range,
// and the next two numbers represent another range. The final number in
// the array is X. The goal of your program is to determine if both ranges
// overlap by at least X numbers
// solution:
const assert = require("assert");
function OverlappingRanges(arr) {
let counter = 0;
for (let i = arr[0]; i < arr[1]; i += 1) {
if (i >= arr[2] && i <= arr[3]) {
counter += 1;
}
}
return counter >= arr[4];
}
const a1 = "[1, 8, 2, 4, 4]"; // input
const r1 = "false"; // output
const t1 = OverlappingRanges(a1);
assert(t1, r1);
// console.log(OverlappingRanges(["1, 8, 2, 4, 4"]));
const a2 = "[5, 11, 1, 5, 1]"; // input
const r2 = "true"; // output
const t2 = OverlappingRanges(a2);
assert.strictEqual(t2, r2);
// objective:
// Take the str parameter being passed and return the string true if the
// parameter is a palindrome, (the string is the same forward as it is backward)
// otherwise return the string false
// solution:
const assert = require("assert");
function Palindrome(str) {
const init = str.split(" ").join("");
const x = init.split("");
const y = x.reverse();
const z = y.join("");
if (z === init) {
return true;
}
return false;
}
const a1 = "A weight, suspended from pivot. It can swing freely.";
const r1 = "false";
const t1 = Palindrome(a1);
console.log(r1);
assert(r1, t1);
// objective:
// Given a string, check if the string can be made palindrome
// by swapping a character only once.
// solution:
const assert = require("assert");
function PalindromeSwapper(str) {
const inputArray = str.split("");
const strLen = inputArray.length;
const palTester = arr => {
const len = arr.length;
for (let i = 0; i < len; i += 1) {
if (arr[i] !== arr[len - (1 + i)]) {
return false;
}
}
return true;
};
for (let i = 0; i < strLen - 1; i += 1) {
const newArray = Array.from(inputArray);
newArray.splice(i, 2, newArray[i + 1], newArray[i]);
if (palTester(newArray)) {
return newArray.join("");
}
// console.log('PalindromeSwapper');
}
return -1;
}
const in1 = "anna"; // input
const expect1 = "anna"; // output
const test1 = PalindromeSwapper(in1);
assert.strictEqual(test1, expect1, `should be ${expect1}`);
console.log(test1);
const in2 = "kayak"; // input
const expect2 = "kayak"; // output
const test2 = PalindromeSwapper(in2);
assert.strictEqual(test2, expect2, `should be ${expect2}`);
console.log(test2);
// objective:
// Take the num parameter being passed which will be an integer
// and return the string true if it's a power of two. If it's not return the string false.
// solution:
const assert = require("assert");
function powersOfTwo(n) {
const powerArray = [];
for (let i = 0; i <= n; i += 1) {
// console.log(Math.pow(2,i));
powerArray.push(Math ** (2, i));
}
console.log(powerArray);
return [];
}
powersOfTwo(0);
powersOfTwo(6);
powersOfTwo(8);
const r1 = "[]";
assert(r1);
// objective:
// Take the str string parameter, which contains single digit numbers, letters, and
// question marks, and check if there are exactly 3 question marks between every pair of
// two numbers that add up to 10. If so, return the string true, otherwise it should
// return the string false. If no two numbers add up to 10, then it returns false.
// solution:
const assert = require("assert");
function QuestionMarks(str) {
let flag = false;
for (let i = 0; i < str.length; i += 1) {
for (let j = i + 1; j < str.length; j += 1) {
if (Number(str[i]) + Number(str[j]) === 10) {
flag = true;
if (str.slice(i, j).split("?").length - 1 < 3) {
return false;
}
}
}
}
return flag;
}
console.log(QuestionMarks('acc?7??sss?3rr1??????5'));
const r1 = "false"; // input
const t1 = QuestionMarks("a??4ikb"); // output
assert(r1, t1);
// objective:
// Determine the area formed by the 4 points.
// The area is the width of the rectangle * the height
// solution:
const assert = require("assert");
function RectangleArea(strArr) {
const points = strArr.map(str => str.match(/\d+/g));
const minX = points.map(point => point[0]).sort()[0];
const minY = points.map(point => point[1]).sort()[0];
const maxX = points
.map(point => point[0])
.sort()
.reverse()[0];
const maxY = points
.map(point => point[1])
.sort()
.reverse()[0];
return (maxX - minX) * (maxY - minY);
}
const a1 = '"(1 1)","(1 3)","(3 1)","(3 3)"'; // input
const r1 = "4"; // output
const t1 = RectangleArea(a1);
assert.strictEqual(t1, r1);
// objective:
// Take the array of numbers stored in arr and return the second lowest
// and second greatest numbers, respectively, separated by a space.
// solution:
const assert = require("assert");
function SecondGreatLow(arr) {
// sort the unique array in ascending order
arr.sort((a, b) => a - b);
// return the second smallest and largest elements
const solution = [];
solution.push(arr[1], arr[arr.length - 2]);
return solution.join(",");
}
console.log(SecondGreatLow([2, 3, 4, 6, 8]));
const t1 = SecondGreatLow;
assert(t1);
// objective:
// Have the func SimpleAdding(num) add up all the numbers from 1 to num.
// ie: if input is 4 then program should return 10 because 1 + 2 + 3 + 4 = 10.
// For the test cases, the parameter num will be any number from 1 to 1000.
// solution:
const assert = require("assert");
function SimpleAdding(num) {
let addedNum = num;
for (let i = 1; i <= num; i += 1) {
// ...adding i to answer each time
addedNum += i;
}
// return answer
return addedNum;
}
const a1 = "4"; // input
const r1 = "10"; // output
const t1 = SimpleAdding(a1);
assert(r1, t1);
// objective:
// Convert a binary number into a decimal number
// solution:
const assert = require("assert");
function SimpleMode(bstr) {
return parseInt((bstr + "").replace(/[^01]/gi, ""), 2);
}
// console.log(SimpleMode("11001")); yields: 25
const a1 = "11001"; // input
const r1 = "25"; // output
const t1 = SimpleMode(a1);
console.log(r1);
// objective:
// Take the str parameter being passed and determine if it is an acceptable sequence by
// either returning the string true or false. The str parameter will be composed of + and =
// symbols with several letters between them (ie. ++d+===+c++==a) and for the string
// to be true each letter must be surrounded by a + symbol. So the string to the left
// would be false. The string will not be empty and will have at least one letter/
// catch invalid strings instead of valid ones
// solution:
const assert = require("assert");
function SimpleSymbols(str) {
if (str[0] >= "a" || str[str.length - 1] >= "a") {
return false;
}
for (let i = 1; i < str.length - 1; i += 1) {
if (str[i] >= "a") {
if (str[i + 1] !== "+" || str[i - 1] !== "+") {
return false;
}
}
}
return true;
}
const a = [
// valid
"++b+===+c++==+a++",
"+a+a+a+",
"+a++a+",
"+a+",
// invalid
"++b+===+c++==a",
"+=b+",
"+bb+",
"+b=+",
"+b+b",
"b+b+"];
const r = /^[+=\d]*\+(?:[a-z]\+[+=\d]*)+$/im;
a.forEach(s => {
console.log(r.test(s));
});
SimpleSymbols("++=+f+4=+s+"); // -> true;
const a1 = "++=+f+4=+s+"; // input
const t1 = SimpleSymbols(a1);
assert(t1);
// Determine if string 1 can be rearranged to match string 2
// Solve by looping through the second string and check if
// each character exists in the first string
// Start: take both parameters being passed and return the string
// true if a portion of str1 characters can be rearranged to match
// str2, otherwise return the string false
const assert = require("assert");
// loop through string 2
function StringScramble(str1, str2) {
for (let i = 0; i < str2.length; i += 1) {
// check if each character also exists in string 1
// if not, return false
if (str1.indexOf(str2.charAt(i)) === -1) {
return false;
}
}
// return true if all characters exist in string 1
return true;
}
console.log(StringScramble('rkqodlw', 'world'));
const in1 = "cdore & str2 = coder"; // input
const r1 = "true"; // output
const test1 = StringScramble(in1);
assert(r1, test1);
const in2 = 'h3llko" & str2 = "hello'; // input
const r2 = "false"; // output
const test2 = StringScramble(in2);
assert(r2, test2);
// objective:
// Determine if every element in an array is greater than the sum of
// all the previous elements. Solve this by simply looping through the array
// while keeping a running sum stored in a variable and checking each element in
// the array against this sum.
// solution:
const assert = require("assert");
function SuperIncreasing(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i += 1) {
if (arr[i] <= sum) {
return "false";
}
sum += arr[i];
}
return true;
}
const a1 = "[1, 2, 3, 4]"; // input
const r1 = "false"; // output
const t1 = SuperIncreasing(a1);
assert.strictEqual(t1, r1);
const a2 = '[1, 2, 5, 10]';
const r2 = 'true';
const t2 = SuperIncreasing(a2);
assert.strictEqual(t2, r2);
// objective:
// Turn the string into an array
// For example: if the input string is "Hello-World", then your program
// should return the string "hELLo-wORLD"
// loop through the array-swap letter cases
// uppercase -> lowercase
// lowercase -> uppercase
// return modified array as a string
const assert = require("assert");
function swapCase(str) {
const chars = str.split("");
for (let i = 0; i < chars.length; i += 1) {
if (chars[i] === chars[i].toUpperCase()) {
chars[i] = chars[i].toLowerCase();
} else if (chars[i] === chars[i].toLowerCase()) {
chars[i] = chars[i].toUpperCase();
}
}
const caseStr = chars.join("");
console.log(caseStr);
return caseStr;
}
const in1 = "Hello-World"; // input
const expect1 = "hELLO-wORLD"; // output
const test1 = swapCase(in1);
assert.strictEqual(test1, expect1, `should be ${expect1}`);
const t2 = swapCase("LengThforC");
assert(t2);
console.log(t2);
// objective:
// Take the array of strings stored in strArr and return the third largest word within
// solution:
const assert = require("assert");
const ThirdGreatest = strArr => {
strArr.sort((a, b) => b.length - a.length);
return strArr[2];
};
console.log(ThirdGreatest([2, 3, 4, 6, 8]));
const t1 = ThirdGreatest;
assert(t1);
// objective:
// Have function TimeConvert(num) take the num
// parameter being passed and return the number of hours
// and minutes the parameter converts to
// solution:
const assert = require("assert");
function timeConvert(num) {
let hours = 0;
let minutes = 0;
for (let i = 0; i <= num; i += 60) {
// loop through number every 60
if (num >= 60) {
// for every 60 add 1 hour
hours += 1;
} else if (num < 60) {
minutes = num;
}
}
let newMinutes = 0;
if (minutes < 10) {
newMinutes = `0${minutes}`;
} else if (minutes > 10) {
newMinutes = minutes;
}
return `${hours}:${newMinutes}`;
}
console.log(timeConvert(141));
const a1 = "63"; // input
const r1 = "1:3"; // output
const t1 = timeConvert(a1);
assert(r1, t1);
// objective:
// Take the str string parameter being passed and
// return the number of vowels the string contains
// solution:
const assert = require("assert");
function countVowels(str) {
Array.from(str).filter(letter => "aeiou".includes(letter)).length;
}
// console.log(countVowels('abcdefghijklmnopqrstuvwxyz')); // 5
// console.log(countVowels('xxx')); // 0
const a1 = "September"; // input
const r1 = "3"; // output
const t1 = countVowels(a1);
console.log(t1);
assert(r1, t1);
// objective:
// sort the array, then rearrange elements into a pattern-
// pick elements from separate sides of array
// solution:
const assert = require('assert');
function WaveSorting(arr) {
const count = {};
for (let i = 0; i < arr.length; i += 1) {
if (count[arr[i]] >= 1) {
count[arr[i]] += 1;
} else {
count[arr[i]] = 1;
}
console.log('a');
let newArr = [];
for (let a in count) {
newArr.push(count[a]);
}
return Math.max(...newArr) > arr.length/2 ? false : true;
}
// console.log(WaveSorting([0, 4, 22, 4, 14, 4, 2])); // true
// console.log(WaveSorting([0, 1, 2, 4, 1, 1, 1])); // false
const a1 = '[0, 1, 2, 4, 1, 4]'; // input
const r1 = 'true'; // output
const t1 = WaveSorting(a1);
assert.strictEqual(t1, r1);
// objective:
// usage: forms the basis for text ananlysis operations,
// you can make visualizations (ex. word cloud).
// Take the str string parameter being passed and return the number of
// words the string contains
// solution:
const assert = require("assert");
function WordCount(str) {
// Turn the input string into an array by
// passing a single space into the .split method
// Return length of new array (answer)
return str.split("").length;
// console.log(WordCount('Hello, happy holidays'));
}
const a1 = "React is awesome"; // input
const t1 = WordCount(a1);
// console.log(t1);
assert(t1, a1);