diff --git a/brainTeasers/waterJugs.md b/brainTeasers/waterJugs.md index 5276fc0..7959353 100644 --- a/brainTeasers/waterJugs.md +++ b/brainTeasers/waterJugs.md @@ -1 +1,19 @@ 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. + +# fill the 3 quart jug + +# pour the 3 quarts into the 5 quart jug + +# flll the 3 quart jug + +# fill the remainder of the 5 quart jug, leaving 1 quart in the 3 quart jug + +# empty the 5 quart jug + +# pour the remaining 1 quart from the 3 quart jug into the 5 quart jug + +# fill the 3 quart jug + +# pour the 3 quarts into the 5 quart jug + +# the 5 quart jug now contains 4 quarts diff --git a/callBackPractice/callBackPractice.js b/callBackPractice/callBackPractice.js index 8f5d9ac..e41be4f 100644 --- a/callBackPractice/callBackPractice.js +++ b/callBackPractice/callBackPractice.js @@ -20,24 +20,31 @@ const foods = ['pineapple', 'mango', 'ribeye', 'curry', 'tacos', 'ribeye', 'mango']; +const firstItem = (arr, cb) => cb(arr[0]); + 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 = (arr, cb) => cb(arr.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 = (arr, cb) => cb(arr[arr.length - 1]); + 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) => { console.log(`The sum is ${sum}.`); @@ -45,6 +52,8 @@ sumNums(5, 10, (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) => { console.log(`The product is ${product}.`); }); @@ -52,6 +61,8 @@ multiplyNums(5, 10, (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 = (arr, item, cb) => cb(arr.indexOf(item) !== -1) + contains(foods, 'ribeye', (result) => { console.log(result ? 'ribeye is in the array' : 'ribeye is not in the array'); }); @@ -59,12 +70,15 @@ contains(foods, 'ribeye', (result) => { // 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 = (arr, cb) => cb(Array.from(new Set(arr))) + 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 = (arr, cb) => arr.forEach((v, i) => cb(v, i)); // <- Instructions never said not to use array builtin methods ;) forEach(foods, (value, index) => { console.log(`${value} is at index ${index}.`); diff --git a/commonCharacters/commonCharacters.js b/commonCharacters/commonCharacters.js index ec31d82..1ef6611 100644 --- a/commonCharacters/commonCharacters.js +++ b/commonCharacters/commonCharacters.js @@ -6,3 +6,20 @@ * Example: commonCharacters('acexivou', 'aegihobu') * * Returns: 'aeiou' */ +const test1 = 'acexivj oujdf'; +const test2 = 'aeg ihobujj'; + +const commonCharacters = (str1, str2) => { + const seen = {}; + let common = ''; + const matches = str1.match(new RegExp('(['+str2+'])', 'g')) + for (let i = 0; i < matches.length; i++){ + if (matches[i] !== ' ' && !seen[matches[i]]) { + common += matches[i]; + seen[matches[i]] = true; + } + } + return common +} + +console.log(commonCharacters(test1, test2)) \ No newline at end of file diff --git a/constructors/constructors.js b/constructors/constructors.js index 54801f6..9499ebd 100644 --- a/constructors/constructors.js +++ b/constructors/constructors.js @@ -1,23 +1,125 @@ -/* Design several classes and their relationships for an RPG videogame. - * Classes: - * NPC -> Humanoid, Animal, Plant - * Humanoid -> Human, Elf, Orc - * Animal -> Bear, Wolf - * Plant -> FleshEatingDaisy - * - * 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. - * - * Humanoid, Animal, and Plant should all inherit from NPC. The classes - * shown to the right of the arrow are classes that will inherit - * from those classes. - * - * Soldier, Peasant, and Bandit should all inherit from Human. - * - * Create properties for these different classes that fit with the character. - * - * 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 + + +/* +* Design several classes and their relationships for an RPG videogame. +* Classes: +* NPC -> Humanoid, Animal, Plant +* Humanoid -> Human, Elf, Orc +* Animal -> Bear, Wolf +* Plant -> FleshEatingDaisy +* +* 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. +* +* Humanoid, Animal, and Plant should all inherit from NPC. The classes +* shown to the right of the arrow are classes that will inherit +* from those classes. +* +* Soldier, Peasant, and Bandit should all inherit from Human. +* +* Create properties for these different classes that fit with the character. +* +* This is how you would structure the game objects in an actual game +* application in Unity or another similar framework. +*/ + +class NPC { + constructor(attr) { + this.hp = attr.hp; + this.strength = attr.strength; + this.speed= attr.speed; + this.attack = attr.attack; + this.defend = attr.defend; + } +} + +class Humanoid extends NPC { + constructor(attr) { + super(attr) + // Humanoid Attributes + this.weapon = attr.weapon; + } +} + +class Animal extends NPC { + constructor(attr) { + super(attr) + // Animal Attributes + } +} + +class Plant extends NPC { + constructor(attr) { + super(attr) + // Plant Attributes + } +} + +class Human extends Humanoid { + constructor(attr) { + super(attr) + // Human Attributes + } +} + +class Elf extends Humanoid { + constructor(attr) { + super(attr) + // Elf Attributes + } +} + +class Orc extends Humanoid { + constructor(attr) { + super(attr) + // Orc Attributes + } +} + +class Bear extends Animal { + constructor(attr) { + super(attr) + // Bear Attributes + } +} + +class Wolf extends Animal { + constructor(attr) { + super(attr) + // Wolf Attributes + } +} + +class FleshEatingDaisy extends Plant { + constructor(attr) { + super(attr) + // FleshEatingDaisy Attributes + } +} + +class Soldier extends Humanoid { + constructor(attr) { + super(attr) + // Soldier Attributes + } +} + +class Peasant extends Humanoid { + constructor(attr) { + super(attr) + // Peasant Attributes + } +} + +class Bandit extends Humanoid { + constructor(attr) { + super(attr) + // Bandit Attributes + } +} + +const sl = new Soldier({hp: 100}) + +console.log(sl) \ No newline at end of file diff --git a/evenOccurences/evenOccurences.js b/evenOccurences/evenOccurences.js index 1943998..f497e6d 100644 --- a/evenOccurences/evenOccurences.js +++ b/evenOccurences/evenOccurences.js @@ -12,4 +12,24 @@ const evenOccurence = (arr) => { // Your code here. + const occurances = {} + let returnVal = null + for (let i = 0; i < arr.length; i++) { + if (occurances['0'+arr[i]]) occurances['0'+arr[i]]++; + else occurances['0'+arr[i]] = 1; + } + const occuranceKeys = Object.keys(occurances); + for (let j = 0; j < occuranceKeys.length; j++) { + if(occurances[occuranceKeys[j]] % 2 === 0) { + returnVal = occuranceKeys[j].splice(0,1); + break; + } + } + Reflect + return returnVal; }; + +const onlyEven = evenOccurence([1, 7, 4, 2, 5, 1, 6, 8, 9, 6, 4, 3, 2, 1]); +console.log(onlyEven); // 4 + +console.log(evenOccurence([1,2,3,4,5])) \ No newline at end of file diff --git a/forLoopTimeout/forLoopTimeout.js b/forLoopTimeout/forLoopTimeout.js index 87522c2..69f0966 100644 --- a/forLoopTimeout/forLoopTimeout.js +++ b/forLoopTimeout/forLoopTimeout.js @@ -5,9 +5,19 @@ // I've been asked this three times in separate interviews. 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); -} \ No newline at end of file + doSetTimeout(i) +} + +function doSetTimeout(i) { + setTimeout(function() { + console.log(i) + }, 0); +} + +// If you don't do something like this (and there are other variations on +// this same idea), then each of the timer handler functions will share the +// same variable "i". When the loop is finished, what's the value of "i"? +// It's 11! +// By using an intermediating function, a copy of the value of the +// variable is made. Since the timeout handler is created in the context of +// that copy, it has its own private "i" to use. \ No newline at end of file diff --git a/isUnique/isUnique.js b/isUnique/isUnique.js index 6c9caf5..a1d3433 100644 --- a/isUnique/isUnique.js +++ b/isUnique/isUnique.js @@ -1,3 +1,34 @@ /* 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 + */ + +// Test Cases +/** + * 'AAABBBCCC' => false + * 'ABCDEFGHI' => true + * 'AaBbCcDdEe' => true + * 'ABCabcABCabc' => false + * '' => true + */ + +// Psuedo Code +/** +* create a new Set with the string char values (which automatically dedupes string chars) +* return set size compared to string length +*/ + +//Solution +const isUnique = (string) => new Set(string).size === string.length + +//Tests +const test1 = 'AAABBBCCC' // => false +const test2 = 'ABCDEFGHI' // => true +const test3 = 'AaBbCcDdEe' // => true +const test4 = 'ABCabcABCabc' // => false +const test5 = '' // => true + +console.log(isUnique(test1)) +console.log(isUnique(test2)) +console.log(isUnique(test3)) +console.log(isUnique(test4)) +console.log(isUnique(test5)) diff --git a/largestPrimePalindrome/largestPrimePalindrome.js b/largestPrimePalindrome/largestPrimePalindrome.js index 4cc99c0..b996dd8 100644 --- a/largestPrimePalindrome/largestPrimePalindrome.js +++ b/largestPrimePalindrome/largestPrimePalindrome.js @@ -1,6 +1,81 @@ /* - * 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 +* 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. +*/ + +//Test 1000 => 929 + +// WAY WAYYY faster +const largestPrimePalindrome = n => { + 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; + } + + for (let i = n; i > 0; i--) { + if (isPrime(i) && isPalindrome(i)) return i; + } +} + +console.log(largestPrimePalindrome(1000)); + +// // WAAAY Faster +// const longestPalindromePrime = (num) => { +// for (let i = num; i > 0; i--) { +// const str = i.toString(); +// if (str === str.split('').reverse().join('')) { +// let j = 2; +// let count = 0; +// while (count === 0 && j <= (i/2)) { +// if (i % j === 0) count++; +// j++; +// } +// if (count === 0) return i; +// } +// } +// }; + +// function isPrime(number) { +// if (number < 2) {return false} +// if (number != Math.round(number)) {return false} +// let isPrime = true; +// for (let i = 2; i <= Math.sqrt(number); i++) { +// if (number % i == 0) {isPrime = false} +// } +// return isPrime; +// } + +// const longestPalindromePrime = (number) => { +// for (let i = 0; i < number; i++){ +// const test = number - i; +// if (isPrime(test)) { +// if (test === parseInt([...test.toString()].reverse().join(''))) { +// return test +// } +// } +// } +// } + +console.log(longestPalindromePrime(500)); \ No newline at end of file diff --git a/longestString/longestString.js b/longestString/longestString.js index 35b887c..99ff108 100644 --- a/longestString/longestString.js +++ b/longestString/longestString.js @@ -2,3 +2,44 @@ * Write a function that accepts an array of strings. * Return the longest string in the array. */ + +// Test Cases +/** + * ['Loooong', 'short', 'abcde'] => 'Loooong' + * ['AAAAAA','BBBB', 'CCCCC', 'DDDDDD'] => 'AAAAAA' + * [] => null + */ + +// Psuedo Code +/** +* function longestString ([strings]) +* if strings array is empty +* return null +* variable longestStringSoFar equals the first element of the string array +* iterate over array of strings +* if current string is longer than longestStringSoFar +* set longestStringSoFar as current string +* return longestStringSoFar +*/ + +// Solution + +const longestString = (strings) => { + let longestStringSoFar = strings[0]; + if (!longestStringSoFar) return null + strings.forEach(string => { + if (string.length > longestStringSoFar.length) { + longestStringSoFar = string; + } + }); + return longestStringSoFar; +} + +// Tests +const test1 = ['Loooong', 'short', 'abcde']; +const test2 = ['AAAAAA','BBBB', 'CCCCC', 'DDDDDD'] +const test3 = [] + +console.log(longestString(test1) === 'Loooong') +console.log(longestString(test2) === 'AAAAAA') +console.log(longestString(test3) === null) diff --git a/meanMedianMode/meanMedianMode.js b/meanMedianMode/meanMedianMode.js index 821fdc0..36021a8 100644 --- a/meanMedianMode/meanMedianMode.js +++ b/meanMedianMode/meanMedianMode.js @@ -2,3 +2,25 @@ * Given an array of numbers calculate the mean, median, and mode. * Return an object with properties for the mean, median, and mode. */ + + const mmmArr = (arr) => { + const o = {nums: {}, mean: 0, median: 0, mode: 0, maxOcc: 0}; + o.total = arr.reduce((t , v) => { + o.nums[v] ? o.nums[v]++ : o.nums[v] = 1; + if (o.nums[v] > o.maxOcc) { + o.maxOcc = o.nums[v]; + o.mode = v + } + o.mean = t / arr.length; + o.median = (arr.length / 2) % 2 ? + (arr[Math.ceil(arr.length / 2)] + arr[Math.floor(arr.length / 2)]) / 2 + : + arr[Math.floor(arr.length / 2) + 1] + return t + v + }) + return o; + } + + const someNums = [1,5,3,4,5,6,6,6,7,8,9,10,11,12,12,4,4] + const result = mmmArr(someNums) + console.log('Mean:', result.mean, 'Median:', result.median, 'Mode:', result.mode) \ No newline at end of file diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..dcbd41a --- /dev/null +++ b/package-lock.json @@ -0,0 +1,11 @@ +{ + "requires": true, + "lockfileVersion": 1, + "dependencies": { + "hyper-atom-dark-transparent": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/hyper-atom-dark-transparent/-/hyper-atom-dark-transparent-1.1.4.tgz", + "integrity": "sha1-KRR1XylndKP4lV1HNOyROjDrzUo=" + } + } +} diff --git a/removeDuplicates/removeDuplicates.js b/removeDuplicates/removeDuplicates.js index 970f719..46d2c09 100644 --- a/removeDuplicates/removeDuplicates.js +++ b/removeDuplicates/removeDuplicates.js @@ -8,6 +8,6 @@ * you're more than likely using a for loop under the hood. */ -const removeDuplicates = (arr) => { - //code here... -}; \ No newline at end of file +const removeDuplicates = (arr) => Array.from(new Set(arr)) + +const test1 = [1, 1, 1, 2, 2, 3, 4, 5, 5] // -> [1, 2, 3, 4, 5] \ No newline at end of file diff --git a/reverseCase/reverseCase.js b/reverseCase/reverseCase.js index f1051f5..86b8775 100644 --- a/reverseCase/reverseCase.js +++ b/reverseCase/reverseCase.js @@ -2,4 +2,35 @@ * 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 + */ + + // Test Cases +/** + * "Hello World" => "hELLO wORLD" + * "i AM a STRING" => "I am A string" + */ + + // Psuedo Code + /** + * split string into an array + * map over string array + * if current char is uppercase + * return char as lowercase + * if current char is lowercase + * return char as uppercase + * join array as string and return + */ + + // Solution + const reversCase = (string) => string + .split('') + .map(c => c.toUpperCase() === c ? c.toLowerCase() : c.toUpperCase()) + .join('') + + + // Tests + const test1 = "Hello World"; + const test2 = "i AM a STRING"; + + console.log(reversCase(test1) === 'hELLO wORLD'); + console.log(reversCase(test2) === 'I am A string'); diff --git a/stringCompression/stringCompression.js b/stringCompression/stringCompression.js index 48db571..b1715ef 100644 --- a/stringCompression/stringCompression.js +++ b/stringCompression/stringCompression.js @@ -4,3 +4,25 @@ // 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). + +const test1 = 'aabcccccaaa' // => 'a2b1c5a3' +const test2 = 'aaaaaaaaaaaccccccdddddddefg' // => 'a11c6d7e1f1g1' +const test3 = 'AaaaBBbCcccDDDd'// 'AaaaBBbCcccDDDd' +const test4 = 'ABCDD'// => 'ABCDD' + +const compressor = (string) => { + const letters = [] + for(let i = 0; i < string.length; i++) { + if (string[i] !== string[i - 1]) { + letters.push(...[string[i], 1]) + } else { + letters[letters.length - 1]++ + } + } + return letters.length > string.length ? string : letters.join('') +} + +console.log(compressor(test1)) +console.log(compressor(test2)) +console.log(compressor(test3)) +console.log(compressor(test4)) \ No newline at end of file diff --git a/vowelCount/vowelCount.js b/vowelCount/vowelCount.js index 27fad79..e1d2e32 100644 --- a/vowelCount/vowelCount.js +++ b/vowelCount/vowelCount.js @@ -2,3 +2,7 @@ * Write a function that returns the count of the total number of vowels in a string. * Example: 'Hello World!' -> 3 */ + + const vowelCounter = str => str.match(/([aeiou])/gi).length + + console.log(vowelCounter('FUuUuuuuuk')) \ No newline at end of file