diff --git a/brainTeasers/waterJugs.md b/brainTeasers/waterJugs.md index 5276fc0..b1814f3 100644 --- a/brainTeasers/waterJugs.md +++ b/brainTeasers/waterJugs.md @@ -1 +1,2 @@ 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 up the five quart jug with water from the three quart jug. Then fill up the three quart jug again. Add water from the three quart jug until you completely fill up the five quart jug. Now dump out the five quart jug and add the quart left over from the three quart jug. Finally fill up the three quart jug again and add it to the one quart within the five quart jug. \ No newline at end of file diff --git a/callBackPractice/callBackPractice.js b/callBackPractice/callBackPractice.js index 8f5d9ac..1ced7ac 100644 --- a/callBackPractice/callBackPractice.js +++ b/callBackPractice/callBackPractice.js @@ -18,32 +18,60 @@ // 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']; => The first item is pineapple +//Create function taking array and callback as arguements +// pass the first item of the array to the callback + 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 foods = ['pineapple', 'mango', 'ribeye', 'curry', 'tacos', 'ribeye', 'mango']; => The length of the array is 7 +// write function +// pass arr.length into 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 foods = ['pineapple', 'mango', 'ribeye', 'curry', 'tacos', 'ribeye', 'mango']; => The last item of the array is mango +//create function +// pass arr at last index to 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 +// 5, 10 => The sum is 15. +// create function +// add numbers together and pass to cb +const sumNums = (n1, n2, cb) => cb(n1 + n2); 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 +//assuming mean multiply two numbers not add +// 5, 10 => The product is 15 +//create function, multiply numbers pass to cb + +const multiplyNums = (n1, n2, cb) => cb(n1 * n2); multiplyNums(5, 10, (product) => { console.log(`The product is ${product}.`); @@ -51,6 +79,11 @@ 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 +// ribeye => ribeye is in the array +// create function +// if array includes string pass true to callback otherwise pass false + +const contains = (array, str, cb) => array.includes(str) ? cb(true) : cb(false); contains(foods, 'ribeye', (result) => { console.log(result ? 'ribeye is in the array' : 'ribeye is not in the array'); @@ -58,13 +91,33 @@ 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. +//['pineapple', 'mango', 'ribeye', 'curry', 'tacos', 'ribeye', 'mango'] = foods with duplicates removed: 'pineapple', 'mango', 'ribeye', 'curry', 'tacos' +// create function +// make new array +// if not present in new array than push to new array + +const removeDuplicates = (array, cb) => { + const uniq = []; + array.forEach((str) => { + if (!uniq.includes(str)) uniq.push(str); + }); + cb(uniq); +} 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. - +// ['pineapple', 'mango', 'ribeye', 'curry', 'tacos', 'ribeye', 'mango'] => pineapple is at index 0, etc... +// create function +// iterate over the array and push the value and index to callback for each element + +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}.`); diff --git a/commonCharacters/commonCharacters.js b/commonCharacters/commonCharacters.js index ec31d82..935278c 100644 --- a/commonCharacters/commonCharacters.js +++ b/commonCharacters/commonCharacters.js @@ -6,3 +6,35 @@ * Example: commonCharacters('acexivou', 'aegihobu') * * Returns: 'aeiou' */ + +// create function +// create new string +// create memo that contains a whitespace as a key value pair (this will contain every character weve seen) +// create an object that will hold the characters from s2 (this will allow us to only iterate throgh s2 once instead of once for every charcter in s1) +// iterate through s2 creating a key value pair in the s2 object +// iterate through s1 +// if it contains a character that is a key in the s2obj and isnt yet in memo then add it to the string common +// add to the common character to the memo so we dont add duplicates +// return common + +//TEST +// commonCharacters('acexivou', 'aegihobu') => "aeiou" +// commonCharacters('ad fsaaa u', 'aefdfa aaaa r u') => "adfu" + +const commonCharacters = (s1, s2) => { + let common = ''; + const memo = { + ' ': ' ' + }; + const s2obj = {}; + for (let j = 0; j < s2.length; j++) { + s2obj[s2[j]] = s2[j]; + } + for (let i = 0; i < s1.length; i++) { + if (s2obj[s1[i]] && !memo[s1[i]]) { + common += s1[i]; + memo[s1[i]] = s1[i]; + } + } + return common; +}; diff --git a/constructors/constructors.js b/constructors/constructors.js index 54801f6..47a91aa 100644 --- a/constructors/constructors.js +++ b/constructors/constructors.js @@ -20,4 +20,90 @@ * * 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 + */ + + /* create initial NPC class + each class than extends the proper class + use super to bring over the attributes from the previous class + pass in arguements + */ + class NPC { + constructor(hp, strength, speed) { + this.hp = hp; + this.strength = strength; + this.speed = speed; + } + } + class Humanoid extends NPC { + constructor(hp, strength, speed, swordsmanship, bowSkills) { + super(hp, strength, speed); + this.swordmanship = swordsmanship; + this.bowSkills = bowSkills + } + } + class Animal extends NPC { + constructor(hp, strength, speed) { + super(hp, strength, speed); + } + } + class Plant extends NPC { + constructor(hp, strength, speed) { + super(hp, strength, speed); + } + } +class Human extends Humanoid { + constructor(swordmanship, hp, strength) { + super(hp || 8, strength || 5, 3, 7, 4); + this.swordmanship = swordmanship || 5; + } +} +class Elf extends Humanoid { + constructor() { + super(7, 4, 5, 3, 9); + this.swordmanship = 5; + } +} +class Orc extends Humanoid { + constructor() { + super(9, 9, 2, 3, 1); + this.swordmanship = 5; + } +} +class Bear extends Animal { + constructor() { + super(10, 8, 3); + } +} +class Wolf extends Animal { + constructor() { + super(3, 3, 8); + } +} +class FleshEatingDaisy extends Plant { + constructor() { + super(10, 10, 10); + this.hunger = 10; + this.size = 1; + } + playerNearby() { + this.size = 10; + } +} +//The playernearby method can be used to increase the size of the daisy when a player enters within a certain range +class Soldier extends Human { + constructor() { + super(8, 7, 7); + this.defense = 6; + } +} +class Peasant extends Human { + constructor() { + super(3, 2, 1); + } +} +class Bandit extends Human { + constructor() { + super(3, 3, 3); + this.thiefery = 8; + } +} \ No newline at end of file diff --git a/evenOccurences/evenOccurences.js b/evenOccurences/evenOccurences.js index 1943998..31ae643 100644 --- a/evenOccurences/evenOccurences.js +++ b/evenOccurences/evenOccurences.js @@ -10,6 +10,29 @@ * * console.log(onlyEven); // 4 * */ + /* + create function + intialize empty object + loop through the array + if the object contains the key then add one to the keys value + if the object doesn't contain the key then create it with a value of 1 + loop through the objects keys + if the key has a value thats even return that value +*/ + +// Test Cases +//[1, 7, 2, 4, 5, 1, 6, 8, 9, 6, 4, 1] => 4 +//[1, 2, 3, 4] => null + const evenOccurence = (arr) => { - // Your code here. + const obj = {}; + for (let i = 0; i < arr.length; i++) { + if (obj[arr[i]]) obj[arr[i]] += 1; + if (!obj[arr[i]]) obj[arr[i]] = 1; + } + for (let key in obj) { + if (obj[key] % 2 === 0) return Number(key); + } + return null; }; + diff --git a/forLoopTimeout/forLoopTimeout.js b/forLoopTimeout/forLoopTimeout.js index 87522c2..90bf968 100644 --- a/forLoopTimeout/forLoopTimeout.js +++ b/forLoopTimeout/forLoopTimeout.js @@ -4,10 +4,24 @@ // The output should be 1, 2, 3, .... 10. Right now it just prints 11. // I've been asked this three times in separate interviews. + +/* +By the time console.log is being called the final value of i is 11 because it has already ran through the loop +this is due to closure +when creating settimeout it gets hoisted to the global scope. i is not within its scope until after the loop runs +this is why creating a function within a loop is bad practice +in es6 let would not have a block scope +*/ for (var i = 1; i <= 10; i++) { + wrapper(i); +} + +function wrapper(num) { 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); + console.log(num); }, 0); -} \ No newline at end of file +}; + +// By setting a function around setTimeout called wrapper we can take i each time 1 is added and +// call wrapper with i as the argument. This i value is being saved at that point in time and +// console logged by setTimeout at each instance \ No newline at end of file diff --git a/isUnique/isUnique.js b/isUnique/isUnique.js index 6c9caf5..1f2d5aa 100644 --- a/isUnique/isUnique.js +++ b/isUnique/isUnique.js @@ -1,3 +1,53 @@ /* 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 + */ + + /*Identify test cases + string = 'abcd' => true + string = 'abcdc' => false + */ + + /* function isUnique + create new string + iterate over string + if newstring does not include original string at index than add it to string + if lengths of string are equal return true + */ + +const isUnique = (string) => { + let uniqueString = ''; + for(let i = 0; i < string.length; i++) { + if(!uniqueString.includes(string[i])) { + uniqueString += string[i]; + } + } + if(string.length === uniqueString.length) { + return true; + } else { + return false; + } +}; + +//Alt +//Changes string to array but more simple +//set a variable to true +//run for each on array of characters +// if character is the array after the first incidence it changes the variable to false +//return the variable +//must set variable because you can not make a return midway through forEach (it will not stop and keep going) + +const uniqAlt = (string) => { + let boo = true; + string.split('').forEach((char, i) => { + if(string.split('').includes(char, i + 1)) { + boo = false; + } + }); + return boo; +}; + +console.log(uniqAlt('abcd')); +console.log(uniqAlt('abcdc')); + +console.log(isUnique('abcd')); +console.log(isUnique('abcdc')); \ No newline at end of file diff --git a/largestPrimePalindrome/largestPrimePalindrome.js b/largestPrimePalindrome/largestPrimePalindrome.js index 4cc99c0..351b7b6 100644 --- a/largestPrimePalindrome/largestPrimePalindrome.js +++ b/largestPrimePalindrome/largestPrimePalindrome.js @@ -3,4 +3,36 @@ * 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 + */ + + /* test cases: + 1000 => 929 + 200 => 191 + 1 => undefined + */ + + // create function that takes in num + // iterate from top down to find the highest number that is a palindrome + // this way for higher numbers you dont have to iterate as far + // set a counter at 0 and j at 2 + // use a while loop to test whether prime + // the while loop will help to cut down on time because as soon as you find out its not + // if the the i is found to be divisible by j the loop is stopped + // also stop the loop once j surpases i/2 because then we know no number beyond that can be evenly divide i + // add one to j each time through + // if no number is found divisible evenly then return that number because it is the highest prime palindrome + + const largestPrimePalindrome = (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; + } + } + }; diff --git a/longestString/longestString.js b/longestString/longestString.js index 35b887c..c0c8e1b 100644 --- a/longestString/longestString.js +++ b/longestString/longestString.js @@ -2,3 +2,20 @@ * Write a function that accepts an array of strings. * Return the longest string in the array. */ + +// 1. identify test cases +// ['abc', 'a', 'b'] -> 'abc' +// ['abc', 'def'] -> 'def' +// [] -> null + +/* +function longestString strings + sort string by length + return string index 0 +*/ + + +const longestString = (strings) => { + strings.sort((a,b) => b.length - a.length) + return strings[0]; +}; \ No newline at end of file diff --git a/meanMedianMode/meanMedianMode.js b/meanMedianMode/meanMedianMode.js index 821fdc0..46c6f84 100644 --- a/meanMedianMode/meanMedianMode.js +++ b/meanMedianMode/meanMedianMode.js @@ -2,3 +2,59 @@ * Given an array of numbers calculate the mean, median, and mode. * Return an object with properties for the mean, median, and mode. */ +// Test Cases +// [1, 2, 4, 3, 4] -> { mean: 2.8, median: 3, mode: 4 } +// [50, 2, 12, 3, 4] -> { mean: 14.2, median: 4, mode: null } +// [2, 3, 4, 3, 2, 4] -> { mean: 3, median: 2.5, mode: [2, 3, 4] } + +/* +create function that takes in an array of numbers + intialize object with mean, median, and mode keys + intitalize an object to keep track on the amount of times weve seen a number + sort the array from least to most + for each + number in the array add it to the mean + if the mode object has the number intialize the number with value 0 + add one to the mode object at that keys value + take the objects mean and divide it by the length of the array to get the mean value + if the array is even the median value will be average of the two middle values + if the array is odd the median value will be the middle value + set variables for an array of the mode objects values and its keys + set a variable for the max number within the values array + if the max times is not equal to 1 run a for each + if the value is equal to the maxtimes value then push the number at that keys index to mode + else set the mode to null + if the maxtimes is greater than 1 and the modes ovject length is one set the mode to the single number within the modes array + return the object + */ + + const meanMedianMode = (arr) => { + const obj = { + mean: null, + median: null, + mode: [], + }; + const modeObj = {} + arr.sort((a, b) => a - b) + arr.forEach((n) => { + obj.mean = obj.mean + n; + if (!modeObj[n]) modeObj[n] = 0; + modeObj[n]++; + }) + obj.mean = obj.mean/arr.length; + if (arr.length % 2 === 0) obj.median = (arr[arr.length/2 - 2] + arr[arr.length/2 - 1])/2 + if (arr.length % 2 !== 0) obj.median = arr[Math.floor(arr.length/2)]; + const values = Object.values(modeObj); + const keys = Object.keys(modeObj); + const maxTimes = Math.max(...values); + if (maxTimes !== 1) { + values.forEach((val, i) => { + if (val === maxTimes) obj.mode.push(Number(keys[i])); + }); + } else { + obj.mode = null; + } + if (maxTimes > 1 && obj.mode.length === 1) obj.mode = obj.mode[0]; + return obj; + } + \ No newline at end of file diff --git a/removeDuplicates/removeDuplicates.js b/removeDuplicates/removeDuplicates.js index 970f719..43a5c02 100644 --- a/removeDuplicates/removeDuplicates.js +++ b/removeDuplicates/removeDuplicates.js @@ -8,6 +8,37 @@ * you're more than likely using a for loop under the hood. */ + /*Test cases + [1, 1, 1, 2, 2, 3, 4, 5, 5] -> [1, 2, 3, 4, 5] + [1,2, 3, 4] -> [1, 2, 3, 4] + [] -> [] + */ + /* remove duplicates function + create new set from array values + return set as array; + */ + const removeDuplicates = (arr) => { - //code here... -}; \ No newline at end of file + return [...new Set(arr)]; +}; + +// +/* Second Way +create an object that remember what numbers we have seen +iterate through the array with for each + if the value does not exist within memo + create the value within memo +return the values of memo +*/ + +const removeDuplicates2 = (arr) => { + const memo = {}; + arr.forEach((a) => { + if(!memo[a]) { + memo[a] = a; + } + }) +return Object.values(memo); +}; + +// should be linear time diff --git a/reverseCase/reverseCase.js b/reverseCase/reverseCase.js index f1051f5..d30df67 100644 --- a/reverseCase/reverseCase.js +++ b/reverseCase/reverseCase.js @@ -2,4 +2,68 @@ * 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 +<<<<<<< HEAD + */ + +// 1. identify test cases +// 'Hello World' -> 'hELLO wORLD' +// 'tE sT' -> 'TeSt' +// '' -> '' + +/* +function reverseCase + new string intitalizes + loop through string + if string.charCodeAt(i) is between 64 and 91 + change letter to lower case add to new string + if letter is between 96 and 123 + change to uppercase add to new string + else + add to new string + */ + +const reverseCase = (string) => { + let newString = ''; + for (let i = 0; i < string.length; i++) { + if (string.charCodeAt(i) > 64 && string.charCodeAt(i) < 91) { + newString += string[i].toLowerCase(); + } + else if (string.charCodeAt(i) > 96 && string.charCodeAt(i) < 123) { + newString += string[i].toUpperCase(); + } + else { + newString += string[i]; + } + } + return newString; +} + +//An alternative way using forEach && push instead of iterating through string +const reverseCaseAlt = (string) => { + const newString = []; + string.split('').forEach((letter) => { + if (letter.toLowerCase() === letter) { + newString.push(letter.toUpperCase()); + } + else if (letter.toUpperCase() === letter) { + newString.push(letter.toLowerCase()); + } + else { + newString.push(letter) + } + }) + return newString.join(''); +} + + +console.log(reverseCase('Hello World')); +console.log(reverseCase('tE sT')); +console.log(reverseCase('')); + + +console.log(reverseCaseAlt('Hello World')); +console.log(reverseCaseAlt('tE sT')); +console.log(reverseCaseAlt('')); +======= + */ +>>>>>>> 152158b7139de760aefdb68c9549bf8a02277400 diff --git a/stringCompression/stringCompression.js b/stringCompression/stringCompression.js index 48db571..d4ea7eb 100644 --- a/stringCompression/stringCompression.js +++ b/stringCompression/stringCompression.js @@ -4,3 +4,33 @@ // 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). + +/* +create function that takes in string + intitialize an empty str + initialize a memo that keeps track of how many times in a row we've seen a value + loop through the string + if it is the first character or the previous character before this one is different + create the character as a key in memo with a value of 1 + if the previous character is the same as the current character + add one to the characters key value in memo + if the next character is different from the current character + add the current character and the amount of times in a row we've seen that character to the new string + if the new string's length is less than the original string return the new string + return the original string +*/ + +//Test Cases +//'aabcccccaaa' => 'a2b1c5a3' +//'aeiou' => 'aeiou' + +const stringCompression = (str) => { + let newstr = ''; + const memo = {}; + for (let i = 0; i < str.length; i++) { + if (i === 0 || str[i - 1] !== str[i]) memo[str[i]] = 1; + if (str[i - 1] === str[i]) memo[str[i]]++; + if (str[i + 1] !== str[i]) newstr += str[i] + memo[str[i]]; + } + return newstr.length < str.length ? newstr : str; +} diff --git a/vowelCount/vowelCount.js b/vowelCount/vowelCount.js index 27fad79..23af38c 100644 --- a/vowelCount/vowelCount.js +++ b/vowelCount/vowelCount.js @@ -2,3 +2,23 @@ * Write a function that returns the count of the total number of vowels in a string. * Example: 'Hello World!' -> 3 */ +/* +write function that takes in string + set count to 0; + loop through string + if the character matches and of the characters a e i o or u (ignoring case) then add 1 to count + return count +*/ + +// Test Cases +// 'Hello World!' -> 3 +// 'fasdRE342;cdsa . d' -> 3 +// ' ' -> 0 + + const vowelCount = (s) => { + let count = 0; + for(let i = 0; i < s.length; i++) { + if (s[i].match(/[aeiou]/i)) count++; + } + return count; + };