diff --git a/brainTeasers/waterJugs.md b/brainTeasers/waterJugs.md index 5276fc0..de27589 100644 --- a/brainTeasers/waterJugs.md +++ b/brainTeasers/waterJugs.md @@ -1 +1,13 @@ You have a five-quart jug, a three-quart jug, and an unlimited supply of water (but no measuring cups). How would you come up with exactly four quarts of water? Note that the jugs are oddly shaped, such that filling up exactly "half" of the jug would be impossible. + + + 5 qt jug │ 3 qt jug + ─────────────┼──────────── + 0 │ 3 fill up 3 quart jug + 3 │ 0 transfer 3 quarts to the 5 quart jug + 3 │ 3 fill up 3 quart jug again + 5 │ 1 fill up the 5 quart jug from the 3 quart jug with 1 quart remaining in the 3 quart jug + 0 │ 1 empty the 5 quart jug + 1 │ 0 transfer 1 quart from the 3 quart jug to the 5 quart jug + 1 │ 3 fill up the 3 quart jug + 4 │ 0 transfer the 3 quart jug to the 5 quart jug to get the desired 4 quarts of water \ No newline at end of file diff --git a/callBackPractice/callBackPractice.js b/callBackPractice/callBackPractice.js index 8f5d9ac..4165ec9 100644 --- a/callBackPractice/callBackPractice.js +++ b/callBackPractice/callBackPractice.js @@ -15,57 +15,74 @@ * */ - // Write a function called firstItem that passes the first item of the given array to the callback function - -const foods = ['pineapple', 'mango', 'ribeye', 'curry', 'tacos', 'ribeye', 'mango']; - -firstItem(foods, (firstItem) => { +const firstItem = (foods, cb) => cb(foods[0]); + +const foods = [ + 'pineapple', + 'mango', + 'ribeye', + 'curry', + 'tacos', + 'ribeye', + 'mango' +]; + +firstItem(foods, firstItem => { console.log(`The first item is ${firstItem}.`); }); // Write a function called getLength that passes the length of the array into the callback +const getLength = (length, cb) => cb(foods.length); -getLength(foods, (length) => { +getLength(foods, length => { console.log(`The length of the array is ${length}.`); }); // Write a function called last which passes the last item of the array into the callback +const last = (foods, cb) => cb(foods[foods.length - 1]); -last(foods, (lastItem) => { +last(foods, lastItem => { console.log(`The last item in the array is ${lastItem}.`); }); // Write a function called sumNums that adds two numbers and passes the result to the callback +const sumNums = (a, b, cb) => cb(a + b); - -sumNums(5, 10, (sum) => { +sumNums(5, 10, sum => { console.log(`The sum is ${sum}.`); }); // Write a function called multiplyNums that adds two numbers and passes the result to the callback +const multiplyNums = (a, b, cb) => cb(a * b); -multiplyNums(5, 10, (product) => { +multiplyNums(5, 10, product => { console.log(`The product is ${product}.`); }); // Write a function called contains that checks if an item is present inside of the given array. // Pass true to the callback if it is, otherwise pass false +const contains = (foods, i, cb) => cb(foods.indexOf(i) > -1); -contains(foods, 'ribeye', (result) => { +contains(foods, 'ribeye', result => { console.log(result ? 'ribeye is in the array' : 'ribeye is not in the array'); }); // Write a function called removeDuplicates that removes all duplicate values from the given array. // Pass the array to the callback function. Do not mutate the original array. +const removeDuplicates = (foods, cb) => cb(Array.from(new Set(foods))); -removeDuplicates(foods, (uniqueFoods) => { +removeDuplicates(foods, uniqueFoods => { console.log(`foods with duplicates removed: ${uniqueFoods}`); }); // Write a function called forEach that iterates over the provided array and passes the value and index into the callback. - +const forEach = (foods, cb) => { + for (let i = 0; i < foods.length; i++) { + cb(foods[i], i); + } +}; forEach(foods, (value, index) => { console.log(`${value} is at index ${index}.`); -}); \ No newline at end of file +}); diff --git a/constructors/constructors.js b/constructors/constructors.js index 54801f6..26e0888 100644 --- a/constructors/constructors.js +++ b/constructors/constructors.js @@ -8,7 +8,7 @@ * Human -> Soldier, Peasant, Bandit * * NPC should be a general class for a non-player character in the game. - * This class will probably include general attributes like hp, strength, speed, etc. + * This class will probably include general attributes like hp, str, speed, etc. * * Humanoid, Animal, and Plant should all inherit from NPC. The classes * shown to the right of the arrow are classes that will inherit @@ -20,4 +20,129 @@ * * This is how you would structure the game objects in an actual game * application in Unity or another similar framework. - */ \ No newline at end of file + */ + +class NPC { + constructor(options) { + this.con = options.con; + this.str = options.str; + this.dex = options.dex; + this.int = options.int; + this.wis = options.wis; + this.cha = options.cha; + } +} + +// Humanoid +// ↳ Human +// ↳ Fighter → Thief → Wizard +// ↳ Elf +// ↳ Ranger → Rogue → Druid +// ↳ Orc +// ↳ Barbarian → Warlock → Shaman +class Humanoid extends NPC { + constructor(options) { + super(options); + } +} + +class Human extends Humanoid { + constructor(options) { + super(options); + this.name = options.name; + } +} + +class Fighter extends Human { + constructor(options) { + super(options); + } +} + +class Thief extends Human { + constructor(options) { + super(options); + } +} + +class Wizard extends Human { + constructor(options) { + super(options); + this.abilities = ['Magic Missile', 'Shock Pulse', 'Spectral Blade', 'Electrocute']; + } +} +class Elf extends NPC { + constructor(options) { + super(options); + } +} + +class Ranger extends Elf { + constructor(options) { + super(options); + } +} + +class Rogue extends Elf { + constructor(options) { + super(options); + } +} + +class Druid extends Elf { + constructor(options) { + super(options); + } +} + +class Orc extends NPC { + constructor(options) { + super(options); + } +} + +class Barbarian extends Orc { + constructor(options) { + super(options); + } +} + +class Warlock extends Orc { + constructor(options) { + super(options); + } +} + +class Shaman extends Orc { + constructor(options) { + super(options); + } +} +// Animal +// ↳ Tiny +// ↳ Rat → Lizard → Hawk +// ↳ Large +// ↳ Brown Bear → Dire Wolf → Horse +// ↳ Huge +// ↳ Giant Octopus → Nemean Lion → Roc +class Animal extends NPC { + constructor(options) { + super(options); + } + } + +// Monster +// ↳ Dragon +// ↳ Adult Dragon → Wyrm → Faerie Dragon +// ↳ Giant +// ↳ Ogre → Ettin → Cyclops +// ↳ Undead +// ↳ Lich → Zombie → Ghoul +class Monster extends NPC { + constructor(options) { + super(options); + } + } + +var frank = new Wizard({ name: 'Frank', con: 4, str: 3, dex: 3, int: 10, wis: 10, cha: 8 }); +console.log(frank); \ No newline at end of file diff --git a/evenOccurences/evenOccurences.js b/evenOccurences/evenOccurences.js index 1943998..1b5babf 100644 --- a/evenOccurences/evenOccurences.js +++ b/evenOccurences/evenOccurences.js @@ -1,15 +1,39 @@ -/* - * * Find the first item that occurs an even number of times in an array. - * * Remember to handle multiple even-occurance items and return the first one. - * * Return null if there are no even-occurance items. - * */ - -/* - * * example usage: - * * const onlyEven = evenOccurance([1, 7, 2, 4, 5, 1, 6, 8, 9, 6, 4, 1]); - * * console.log(onlyEven); // 4 - * */ +/* Instructions + * Find the first item that occurs an even number of times in an array. + * Remember to handle multiple even-occurance items and return the first one. + * Return null if there are no even-occurance items. + */ +// Test Cases +const onlyEven = [1, 7, 2, 4, 5, 1, 6, 8, 9, 6, 4, 1]; // 4 + +// Solution #1 const evenOccurence = (arr) => { - // Your code here. -}; + let a = [...new Set(arr)], + b = 0; + for (i in a) { + b = 0; + for (j in arr) { + if (a[i] === arr[j]) { + b++; + } + } + if (b % 2 === 0) return a[i]; + } + return null; +} + +// Solution #2 +// const evenOccurence = arr => { +// let a = {}; +// arr.forEach((i) => { +// if (a[i]) a[i] += 1; +// else a[i] = 1; +// }) +// for (let k in a) { +// if (a[k] % 2 === 0) return Number(k); +// } +// return null; +// }; + +console.log(evenOccurence(onlyEven)); diff --git a/forLoopTimeout/forLoopTimeout.js b/forLoopTimeout/forLoopTimeout.js index 87522c2..bb752b1 100644 --- a/forLoopTimeout/forLoopTimeout.js +++ b/forLoopTimeout/forLoopTimeout.js @@ -1,13 +1,33 @@ +// 1. Instructions // Explain what is wrong with this code and how you would fix this. // With ES6 there is a very, very simple way to solve this. // See if you can solve this with just ES5 JS. // The output should be 1, 2, 3, .... 10. Right now it just prints 11. // I've been asked this three times in separate interviews. +// 2a. Solution: ES6 fix. let instead of var encloses the scope of i to the for loop +// for (let i = 1; i <= 10; i++) { +// setTimeout(() => console.log(i), 0); +// } + +// 2b. Solution: Passing a new copy of i with each iteration to setTimeout function callback +// function x(i) { +// setTimeout(() => console.log(i), 0) +// } +// for (var i = 1; i <= 10; i++) { +// x(i); +// } + +// 2c. Solution: New scope for each iteration using IIFE, setTimeout function callback +// provided a variable j that evaluates to i within the scope of for loop +// for (var i = 1; i <= 10; i++) { +// (() => { +// var j = i; +// setTimeout(() => console.log(j), 0); +// })(); +// } + +// 2d. Solution: New scope for each iteration using IIFE (passing i as an argument) for (var i = 1; i <= 10; i++) { - setTimeout(function() { - // From looking at the code you would assume it would print 1 - 10 - // It doesn't. Why? How can you make it print 1 - 10. - console.log(i); - }, 0); + ((i) => setTimeout(() => console.log(i), 0))(i); } \ No newline at end of file diff --git a/isUnique/isUnique.js b/isUnique/isUnique.js index 6c9caf5..c551b83 100644 --- a/isUnique/isUnique.js +++ b/isUnique/isUnique.js @@ -1,3 +1,41 @@ -/* Implement an algorithm to determine if a string has all unique characters. +/* 0. Instructions + * Implement an algorithm to determine if a string has all unique characters. * What if you cannot use additional data structures? - */ \ No newline at end of file + */ + +// 1. Identify Test Cases +// const a = 'Bacon ipsum dolor amet spare ribs drumstick strip steak.' // false +// const b = 'HeLLo WORLd!' // false +// const c = 'bvAlh!(@^$%#)atQBq' // true + +/* 2. Pseudo-Code + * function with string param + * initialize empty string + * store unique characters in empty string + * compare new string with original string + * return true if has unique characters, otherwise return false + */ + +// 3a. Solution using for loop / indexOf() +const isUnique = str => { + let x = ''; + + for (let i = 0; i < str.length; i++) { + if (x.indexOf(str[i]) === -1) { + x += str[i]; + } + } + console.log(x === str); // return true if string contains unique characters +}; + +// 3b. Solution using an Array.from() / new Set() / .join() +const isUnique = str => { + const x = Array.from(new Set(str)).join(''); + console.log(x === str); // return true if string contains unique characters +}; + +// 3c. Solution using spread operator / new Set() / .join() +const isUnique = str => { + const x = [...new Set(str)].join(''); + console.log(x === str); // return true if string contains unique characters +}; diff --git a/largestPrimePalindrome/largestPrimePalindrome.js b/largestPrimePalindrome/largestPrimePalindrome.js index 4cc99c0..3fbbb1c 100644 --- a/largestPrimePalindrome/largestPrimePalindrome.js +++ b/largestPrimePalindrome/largestPrimePalindrome.js @@ -1,6 +1,34 @@ -/* - * Create a function that returns the largest prime palindrome less than 1000. - * Hint: it's 929 - * You will first want to determine if the number is a palindrome and then determine if it is prime. - * A palindrome is a number that is the same forwards and backwards: 121, 323, 123454321, etc. - */ \ No newline at end of file +const isPrime = n => { + let divisor = 3, + limit = Math.sqrt(n); + + if (n === 2 || n === 3) return true; + if (n % 2 === 0) return false; + + while (divisor <= limit) { + if (n % divisor === 0) return false; + else divisor += 2; + } + return true; +} + +const isPalindrome = n => { + let str = n.toString(), + len = str.length; + + for (let i = 0; i < len / 2; i++) { + if (str[i] !== str[len -1 -i]) + return false; + } + return true; +} + +const largestPrimePalindrome = n => { + for (let i = n; i > 0; i--) { + if (isPrime(i) && isPalindrome(i)) return i; + } +} + +console.log(largestPrimePalindrome(1000)) + + diff --git a/longestString/longestString.js b/longestString/longestString.js index 35b887c..2bedaf4 100644 --- a/longestString/longestString.js +++ b/longestString/longestString.js @@ -1,4 +1,37 @@ -/* +/* 0. Instructions * Write a function that accepts an array of strings. * Return the longest string in the array. */ + +/* 1. Identify Test Cases + const a = ['abc', 'a', 'b'] // -> 'abc' + const b = ['abc', 'def'] // -> 'def' + const c = [] // -> null + const d = ['asdfasfas', 'sdfadfsa', 'asfasfasdfasfasfd', 's'] // -> 'asfasfasdfasfasfd' +*/ + +/* 2. Pseudo-Code +function longestString strings + loop over the array of strings + do something in the loop + return longestString +*/ + +/* 3a. Solution #1 +const longestStr = (arr) => { + let x = ''; + for (let i = 0; i < arr.length; i++) { + if (arr[i].length > x.length) x = arr[i]; + } + return x; +}; +*/ + +// 3b. Solution #2 +const longestStr = (arr) => { + let x = arr[0]; + arr.forEach(i => { + if (i.length > x.length) x = i; + }); + return x; +} \ No newline at end of file diff --git a/meanMedianMode/meanMedianMode.js b/meanMedianMode/meanMedianMode.js index 821fdc0..85b24ea 100644 --- a/meanMedianMode/meanMedianMode.js +++ b/meanMedianMode/meanMedianMode.js @@ -1,4 +1,55 @@ -/* +/* Instructions * Given an array of numbers calculate the mean, median, and mode. * Return an object with properties for the mean, median, and mode. */ + +/* Mean: Sum of values of a data set divided by number of values. + * Median: Middle value separating the greater and lesser halves of a data set + * Mode: Most frequent value in a data set + */ + +// Test Case +const a = [13, 18, 13, 14, 13, 16, 14, 21, 13]; // odd number of elements +// const a = [13, 18, 13, 14, 13, 16, 14, 21]; // even number of elements + +// Solution +const mean = arr => { + let sum = 0, + i; + for (i = 0; i < arr.length; i++) { + sum += arr[i]; + } + return sum / arr.length; +}; + +const median = arr => { + let median = 0, + len = arr.length; + arr.sort(); + if (len % 2 === 0) median = (arr[len / 2 - 1] + arr[len / 2]) / 2; + else median = arr[(len - 1) / 2]; + return median; +}; + +const mode = arr => { + const seen = {}; + arr.forEach(i => { + if (seen[i] === undefined) return (seen[i] = 1); + if (seen[i] !== undefined) return (seen[i] += 1); + }); + const tmp = Object.values(seen), + mode = tmp.reduce((a, b) => Math.max(a, b)); + return mode; + // return Math.max.apply(null, Object.values(seen)); +}; + +class MeanMedianMode { + constructor(options) { + this.mean = options.mean; + this.median = options.median; + this.mode = options.mode; + } +} + +const obj = new MeanMedianMode({ mean: mean(a), median: median(a), mode: mode(a) }); +console.log(obj); \ No newline at end of file diff --git a/removeDuplicates/removeDuplicates.js b/removeDuplicates/removeDuplicates.js index 970f719..bf1f734 100644 --- a/removeDuplicates/removeDuplicates.js +++ b/removeDuplicates/removeDuplicates.js @@ -1,4 +1,4 @@ -/* +/* 0. Instructions * Write a function that takes an array and removes all duplicate items. * [1, 1, 1, 2, 2, 3, 4, 5, 5] -> [1, 2, 3, 4, 5] * @@ -8,6 +8,39 @@ * you're more than likely using a for loop under the hood. */ +// 1. Identify Test Cases +const a = [1, 1, 1, 2, 2, 3, 4, 5, 5] // -> [1, 2, 3, 4, 5] +const b = ["spray", "spray", "limit", "elite", "elite", "exuberant", "destruction", "present"] + +// 2a. Solution #1 using for loop const removeDuplicates = (arr) => { - //code here... -}; \ No newline at end of file + let seen = {}; + let result = []; + let j = 0; + for (let i = 0; i < arr.length; i++) { + if (seen[arr[i]] !== 1) { + seen[arr[i]] = 1; + result[j++] = arr[i]; + } + } + return result; +} + +console.log(removeDuplicates(a)) +console.log(removeDuplicates(b)) + +// 2b. Solution #1 +// const removeDuplicates = (arr) => { +// return arr.filter((element, index, array) => { // filter creates new array from elements that return true +// return !index || element != array[index - 1]; +// }) +// }; + +// console.log(removeDuplicates(a)) +// console.log(removeDuplicates(b)) + +// 2c. Solution #3 using new Set(); +// const removeDuplicates = (arr) => Array.from(new Set(arr)); + +// console.log(removeDuplicates(a)) +// console.log(removeDuplicates(b)) \ No newline at end of file diff --git a/reverseCase/reverseCase.js b/reverseCase/reverseCase.js index f1051f5..9890ba3 100644 --- a/reverseCase/reverseCase.js +++ b/reverseCase/reverseCase.js @@ -1,5 +1,38 @@ -/* +/* 0. Instructions * Write a function that reverses the case of each letter in the strings that it receives. * Example: 'Hello World' -> 'hELLO wORLD' * Assume that each string will contain only spaces and letters. - */ \ No newline at end of file + */ + +/* 1. Identify Test Cases + * const a = 'Bacon ipsum dolor amet spare ribs drumstick strip steak.' + * const b = 'HeLLo WoRLd!' + * const c = 'bvAlhatQBq' + */ + +/* 2. Pseudo-Code + * function reverseCase str + * initialize empty String variable + * loop over str + * store each element of str in variable n + * if element n is uppercase, convert to lowercase, otherwise convert to uppercase + * store that element into s + * return s + */ + +// 3a. Solution Using .split(), .map(), .join() +const reverseCase = str => + str + .split('') + .map(x => (x === x.toUpperCase() ? x.toLowerCase() : x.toUpperCase())) + .join(''); + +// 3b. Solution Using for loop +const reverseCase = str => { + let s = ''; + for (let i = 0; i < str.length; i++) { + let n = str.charAt(i); + s += n === n.toUpperCase() ? n.toLowerCase() : n.toUpperCase(); + } + return s; +}; diff --git a/stringCompression/stringCompression.js b/stringCompression/stringCompression.js index 48db571..a9a3f02 100644 --- a/stringCompression/stringCompression.js +++ b/stringCompression/stringCompression.js @@ -4,3 +4,59 @@ // If the "compressed" string would not become smaller than the original string, // your method should return the original string. // You can assume the string has only uppercase and lowercase letters (a - z). + +// Test Case +const a = "aabcccccaaa"; // 'a2b1c5a3' +const b = "qwertyuiop"; // 'qwertyuiop' + +// Solution +const stringCompression = str => { + let a = [], + count = 1, + i; + for (i = 0; i < str.length; i++) { + if (str[i] === str[i + 1]) { + count++; + } else if (str[i] !== str[i + 1]) { + a.push(`${str[i]}${count}`); + count = 1; + } + } + // added conditional check to see if "compressed" string is longer than original string + const result = a.join(''); + return result.length >= str.length ? str : result; +}; + +console.log(stringCompression(a)); + +// Tai's Solution + // currentChar = null + // compressedString = '' + // charCount = 1 + // use a for loop, i = 0, until string.length, i++ + // if string.charAt(i) is equal to currentChar, charCount++ + // if (currentChar === null, currentChar = string.charAt(i) + // if (string.charAt(i) !== currentChar || string.charAt(i) === undefined + // compressedString += currentChar; + // compressedString += charCount; + // charCount = 1; + // currentChar = string.charAt(i); + // return using ternary statement (compressedString.length > string.length ? string + // : compressedString; +// const compressString = (string) => { +// let currentChar = string.charAt(0); +// let compressedString = ''; +// let charCount = 0; +// for (let i = 0; i <= string.length; i++) { +// if (string.charAt(i) === currentChar) charCount++; +// if (string.charAt(i) !== currentChar || string.charAt(i) === undefined) { +// compressedString += currentChar; +// compressedString += charCount; +// charCount = 1; +// currentChar = string.charAt(i); +// } +// } +// return compressedString.length > string.length ? string : compressedString; +// }; + +// console.log(compressString('qwertyuiop')); \ No newline at end of file diff --git a/vowelCount/vowelCount.js b/vowelCount/vowelCount.js index 27fad79..a88322f 100644 --- a/vowelCount/vowelCount.js +++ b/vowelCount/vowelCount.js @@ -1,4 +1,29 @@ -/* +/* Instructions * Write a function that returns the count of the total number of vowels in a string. * Example: 'Hello World!' -> 3 */ + +// Test Case +const a = 'Hello World!'; // 3 +const b = ''; // 0 +const c = 'Disrupt jean shorts viral hella meh, plaid cupidatat magna art pArty.' // 20 + +// Solution using match() and RegEx +const vowelCount = str => (str.match(/[aeiou]/gi) || []).length; + +// Solution using Array.from(), filter() and includes() +// const vowelCount = str => Array.from(str).filter(i => 'aeiouAEIOU'.includes(i)).length; + +// Sean's Solution using Set +// const vowelCount = str => { +// const vowels = new Set(['a','e','i','o','u','A','E','I','O','U']); +// let count = 0; +// for (let i = 0; i < str.length; i++) { +// if (vowels.has(str[i])) count++; +// } +// return count; +// } + +console.log(vowelCount(a)); +console.log(vowelCount(b)); +console.log(vowelCount(c)); \ No newline at end of file