From 65d3463c27df5ec335cbd3f4dda2c422a7a2fa17 Mon Sep 17 00:00:00 2001 From: rabobahago Date: Fri, 6 Jan 2023 18:08:16 +0100 Subject: [PATCH] more solution javascript basic added --- elementaryAlgo/ASCII.js | 3 + .../arrayOfPairsFromObject.js | 4 + .../displayAllPropertyOfnestedObjec.js | 11 + .../excludePropUsinJSON.js | 18 + .../JavaScriptCodeChallenge/firstLastChar.js | 10 + .../JavaScriptCodeChallenge/howToEmptyObj.js | 7 + .../JavaScriptCodeChallenge/objectCopy.js | 34 ++ .../replaceThreeCenter.js | 24 ++ .../reverseEachWord.js | 6 + .../JavaScriptCodeChallenge/reverseNum.js | 4 + .../threeWaysToLoopStr.js | 37 +++ .../waysToCreateObject.js | 111 +++++++ elementaryAlgo/addTwoNumber.js | 4 + elementaryAlgo/alvin/alternateCap.js | 17 + elementaryAlgo/alvin/bleepVowels.js | 19 ++ elementaryAlgo/alvin/chooseDivisible.js | 16 + elementaryAlgo/alvin/combinations.js | 16 + elementaryAlgo/alvin/commonElement.js | 21 ++ elementaryAlgo/alvin/divisors.js | 15 + elementaryAlgo/alvin/filterLongWords.js | 17 + elementaryAlgo/alvin/ifelse.js | 14 + elementaryAlgo/alvin/lengthiestWord.js | 18 + elementaryAlgo/alvin/makeAcronyms.js | 15 + elementaryAlgo/alvin/makeMatrix.js | 37 +++ elementaryAlgo/alvin/maximum.js | 14 + elementaryAlgo/alvin/nested.js | 46 +++ elementaryAlgo/alvin/numOdd.js | 13 + elementaryAlgo/alvin/number.js | 14 + elementaryAlgo/alvin/numberRange.js | 13 + elementaryAlgo/alvin/pairPrint.js | 25 ++ elementaryAlgo/alvin/permutations.js | 22 ++ elementaryAlgo/alvin/print2d.js | 36 ++ elementaryAlgo/alvin/printCombination.js | 32 ++ elementaryAlgo/alvin/recursionArray.js | 20 ++ elementaryAlgo/alvin/removeFirstVowel.js | 18 + elementaryAlgo/alvin/removeShortWords.js | 15 + elementaryAlgo/alvin/reverseArray.js | 12 + elementaryAlgo/alvin/smallestNum.js | 12 + elementaryAlgo/alvin/stayPositive.js | 15 + elementaryAlgo/alvin/string.js | 58 ++++ elementaryAlgo/alvin/stringToLength.js | 15 + elementaryAlgo/alvin/total.js | 22 ++ elementaryAlgo/alvin/totalProducts.js | 24 ++ elementaryAlgo/alvin/twoSum.js | 15 + elementaryAlgo/alvin/twoSumPairs.js | 18 + elementaryAlgo/alvin/wordCount.js | 15 + elementaryAlgo/alvin/yourAverageFunc.js | 16 + elementaryAlgo/alvin/zipper.js | 41 +++ elementaryAlgo/areaOfTriangle.js | 16 + elementaryAlgo/calculator.js | 33 ++ elementaryAlgo/countCharacters.js | 11 + elementaryAlgo/generateRandomString.js | 17 + elementaryAlgo/highCommonFactor.js | 24 ++ elementaryAlgo/isLastDigitSame.js | 12 + elementaryAlgo/lowestCommonMultiple.js | 13 + elementaryAlgo/multiplicationTable.js | 10 + elementaryAlgo/printHelloWorld.js | 5 + elementaryAlgo/raboAlgo/binarySearch.js | 36 ++ elementaryAlgo/raboAlgo/binaryTreeProblems.js | 182 +++++++++++ elementaryAlgo/raboAlgo/bubbleSort.js | 18 + elementaryAlgo/raboAlgo/cartesianProduct.js | 11 + elementaryAlgo/raboAlgo/climbingStaircase.js | 15 + elementaryAlgo/raboAlgo/hasTable.js | 70 ++++ elementaryAlgo/raboAlgo/insertionSort.js | 22 ++ elementaryAlgo/raboAlgo/islandCountBFS.js | 57 ++++ elementaryAlgo/raboAlgo/islandCountDFS.js | 52 +++ elementaryAlgo/raboAlgo/linkListClass.js | 308 ++++++++++++++++++ elementaryAlgo/raboAlgo/linkedListProblems.js | 193 +++++++++++ elementaryAlgo/raboAlgo/mergeSort.js | 32 ++ elementaryAlgo/raboAlgo/numOfminutes.js | 38 +++ elementaryAlgo/raboAlgo/numberOfIsland.js | 30 ++ elementaryAlgo/raboAlgo/orangesRotting.js | 75 +++++ elementaryAlgo/raboAlgo/quickSort.js | 20 ++ elementaryAlgo/raboAlgo/twoCrystalBalls.js | 20 ++ .../raboAlgo/twoDArrayOrMatrixBFS.js | 39 +++ .../raboAlgo/twoDArrayOrMatrixDFS.js | 82 +++++ elementaryAlgo/raboAlgo/twoDBasic.js | 14 + elementaryAlgo/raboAlgo/wallsandGates.js | 58 ++++ elementaryAlgo/randomIntegers.js | 10 + elementaryAlgo/replaceAllOcurrenceStr.js | 10 + elementaryAlgo/setOperations.js | 42 +++ elementaryAlgo/splitArrayIntoChunks.js | 18 + elementaryAlgo/squareRoot.js | 5 + elementaryAlgo/strInAnotherStr.js | 8 + elementaryAlgo/sum.js | 20 ++ elementaryAlgo/swapTwoVariable.js | 35 ++ 86 files changed, 2670 insertions(+) create mode 100644 elementaryAlgo/ASCII.js create mode 100644 elementaryAlgo/JavaScriptCodeChallenge/arrayOfPairsFromObject.js create mode 100644 elementaryAlgo/JavaScriptCodeChallenge/displayAllPropertyOfnestedObjec.js create mode 100644 elementaryAlgo/JavaScriptCodeChallenge/excludePropUsinJSON.js create mode 100644 elementaryAlgo/JavaScriptCodeChallenge/firstLastChar.js create mode 100644 elementaryAlgo/JavaScriptCodeChallenge/howToEmptyObj.js create mode 100644 elementaryAlgo/JavaScriptCodeChallenge/objectCopy.js create mode 100644 elementaryAlgo/JavaScriptCodeChallenge/replaceThreeCenter.js create mode 100644 elementaryAlgo/JavaScriptCodeChallenge/reverseEachWord.js create mode 100644 elementaryAlgo/JavaScriptCodeChallenge/reverseNum.js create mode 100644 elementaryAlgo/JavaScriptCodeChallenge/threeWaysToLoopStr.js create mode 100644 elementaryAlgo/JavaScriptCodeChallenge/waysToCreateObject.js create mode 100644 elementaryAlgo/addTwoNumber.js create mode 100644 elementaryAlgo/alvin/alternateCap.js create mode 100644 elementaryAlgo/alvin/bleepVowels.js create mode 100644 elementaryAlgo/alvin/chooseDivisible.js create mode 100644 elementaryAlgo/alvin/combinations.js create mode 100644 elementaryAlgo/alvin/commonElement.js create mode 100644 elementaryAlgo/alvin/divisors.js create mode 100644 elementaryAlgo/alvin/filterLongWords.js create mode 100644 elementaryAlgo/alvin/ifelse.js create mode 100644 elementaryAlgo/alvin/lengthiestWord.js create mode 100644 elementaryAlgo/alvin/makeAcronyms.js create mode 100644 elementaryAlgo/alvin/makeMatrix.js create mode 100644 elementaryAlgo/alvin/maximum.js create mode 100644 elementaryAlgo/alvin/nested.js create mode 100644 elementaryAlgo/alvin/numOdd.js create mode 100644 elementaryAlgo/alvin/number.js create mode 100644 elementaryAlgo/alvin/numberRange.js create mode 100644 elementaryAlgo/alvin/pairPrint.js create mode 100644 elementaryAlgo/alvin/permutations.js create mode 100644 elementaryAlgo/alvin/print2d.js create mode 100644 elementaryAlgo/alvin/printCombination.js create mode 100644 elementaryAlgo/alvin/recursionArray.js create mode 100644 elementaryAlgo/alvin/removeFirstVowel.js create mode 100644 elementaryAlgo/alvin/removeShortWords.js create mode 100644 elementaryAlgo/alvin/reverseArray.js create mode 100644 elementaryAlgo/alvin/smallestNum.js create mode 100644 elementaryAlgo/alvin/stayPositive.js create mode 100644 elementaryAlgo/alvin/string.js create mode 100644 elementaryAlgo/alvin/stringToLength.js create mode 100644 elementaryAlgo/alvin/total.js create mode 100644 elementaryAlgo/alvin/totalProducts.js create mode 100644 elementaryAlgo/alvin/twoSum.js create mode 100644 elementaryAlgo/alvin/twoSumPairs.js create mode 100644 elementaryAlgo/alvin/wordCount.js create mode 100644 elementaryAlgo/alvin/yourAverageFunc.js create mode 100644 elementaryAlgo/alvin/zipper.js create mode 100644 elementaryAlgo/areaOfTriangle.js create mode 100644 elementaryAlgo/calculator.js create mode 100644 elementaryAlgo/countCharacters.js create mode 100644 elementaryAlgo/generateRandomString.js create mode 100644 elementaryAlgo/highCommonFactor.js create mode 100644 elementaryAlgo/isLastDigitSame.js create mode 100644 elementaryAlgo/lowestCommonMultiple.js create mode 100644 elementaryAlgo/multiplicationTable.js create mode 100644 elementaryAlgo/printHelloWorld.js create mode 100644 elementaryAlgo/raboAlgo/binarySearch.js create mode 100644 elementaryAlgo/raboAlgo/binaryTreeProblems.js create mode 100644 elementaryAlgo/raboAlgo/bubbleSort.js create mode 100644 elementaryAlgo/raboAlgo/cartesianProduct.js create mode 100644 elementaryAlgo/raboAlgo/climbingStaircase.js create mode 100644 elementaryAlgo/raboAlgo/hasTable.js create mode 100644 elementaryAlgo/raboAlgo/insertionSort.js create mode 100644 elementaryAlgo/raboAlgo/islandCountBFS.js create mode 100644 elementaryAlgo/raboAlgo/islandCountDFS.js create mode 100644 elementaryAlgo/raboAlgo/linkListClass.js create mode 100644 elementaryAlgo/raboAlgo/linkedListProblems.js create mode 100644 elementaryAlgo/raboAlgo/mergeSort.js create mode 100644 elementaryAlgo/raboAlgo/numOfminutes.js create mode 100644 elementaryAlgo/raboAlgo/numberOfIsland.js create mode 100644 elementaryAlgo/raboAlgo/orangesRotting.js create mode 100644 elementaryAlgo/raboAlgo/quickSort.js create mode 100644 elementaryAlgo/raboAlgo/twoCrystalBalls.js create mode 100644 elementaryAlgo/raboAlgo/twoDArrayOrMatrixBFS.js create mode 100644 elementaryAlgo/raboAlgo/twoDArrayOrMatrixDFS.js create mode 100644 elementaryAlgo/raboAlgo/twoDBasic.js create mode 100644 elementaryAlgo/raboAlgo/wallsandGates.js create mode 100644 elementaryAlgo/randomIntegers.js create mode 100644 elementaryAlgo/replaceAllOcurrenceStr.js create mode 100644 elementaryAlgo/setOperations.js create mode 100644 elementaryAlgo/splitArrayIntoChunks.js create mode 100644 elementaryAlgo/squareRoot.js create mode 100644 elementaryAlgo/strInAnotherStr.js create mode 100644 elementaryAlgo/sum.js create mode 100644 elementaryAlgo/swapTwoVariable.js diff --git a/elementaryAlgo/ASCII.js b/elementaryAlgo/ASCII.js new file mode 100644 index 0000000..680409d --- /dev/null +++ b/elementaryAlgo/ASCII.js @@ -0,0 +1,3 @@ +console.log("a".codePointAt(0)); +console.log("a".charCodeAt(0)); +console.log(String.fromCharCode(97)); diff --git a/elementaryAlgo/JavaScriptCodeChallenge/arrayOfPairsFromObject.js b/elementaryAlgo/JavaScriptCodeChallenge/arrayOfPairsFromObject.js new file mode 100644 index 0000000..805a93a --- /dev/null +++ b/elementaryAlgo/JavaScriptCodeChallenge/arrayOfPairsFromObject.js @@ -0,0 +1,4 @@ +let obj = { name: "rabo", age: 44 }; +const map = new Map(Object.entries(obj)); +console.log(map); +console.log(Object.entries(obj)); diff --git a/elementaryAlgo/JavaScriptCodeChallenge/displayAllPropertyOfnestedObjec.js b/elementaryAlgo/JavaScriptCodeChallenge/displayAllPropertyOfnestedObjec.js new file mode 100644 index 0000000..659517c --- /dev/null +++ b/elementaryAlgo/JavaScriptCodeChallenge/displayAllPropertyOfnestedObjec.js @@ -0,0 +1,11 @@ +let obj = { name: "rabo", detail: { age: 70, bank: { byy: 6667, num: 6667 } } }; +const allProperties = (obj) => { + for (let prop in obj) { + if (typeof obj[prop] !== "object") { + console.log(prop + " " + obj[prop] + ""); + } else { + allProperties(obj[prop]); + } + } +}; +console.log(allProperties(obj)); diff --git a/elementaryAlgo/JavaScriptCodeChallenge/excludePropUsinJSON.js b/elementaryAlgo/JavaScriptCodeChallenge/excludePropUsinJSON.js new file mode 100644 index 0000000..8f86e67 --- /dev/null +++ b/elementaryAlgo/JavaScriptCodeChallenge/excludePropUsinJSON.js @@ -0,0 +1,18 @@ +const obj = { + id: 1, + username: "Rabo", + email: "raboyus@agmail.com", + password: "password35678", +}; +//copy the obj while excluding password +console.log(JSON.stringify(obj, ["id", "username", "email"])); +console.log(JSON.parse(JSON.stringify(obj, ["id", "username", "email"]))); + +//another way +console.log( + JSON.parse( + JSON.stringify(obj, (key, value) => + key === "password" ? undefined : value + ) + ) +); diff --git a/elementaryAlgo/JavaScriptCodeChallenge/firstLastChar.js b/elementaryAlgo/JavaScriptCodeChallenge/firstLastChar.js new file mode 100644 index 0000000..b7aa3be --- /dev/null +++ b/elementaryAlgo/JavaScriptCodeChallenge/firstLastChar.js @@ -0,0 +1,10 @@ +function getTheGapX(str) { + if (!str.includes("X")) { + return -1; + } + const firstIndex = str.indexOf("X"); + const lastIndex = str.lastIndexOf("X"); + return firstIndex === lastIndex ? -1 : lastIndex - firstIndex; +} +console.log(getTheGapX("JavaScript")); +getTheGapX("Xamarin"); diff --git a/elementaryAlgo/JavaScriptCodeChallenge/howToEmptyObj.js b/elementaryAlgo/JavaScriptCodeChallenge/howToEmptyObj.js new file mode 100644 index 0000000..0ea2d42 --- /dev/null +++ b/elementaryAlgo/JavaScriptCodeChallenge/howToEmptyObj.js @@ -0,0 +1,7 @@ +let ob = { name: "9" }; +for (let key in ob) { + if (ob.hasOwnProperty(key)) { + delete ob[key]; + } +} +console.log(ob); diff --git a/elementaryAlgo/JavaScriptCodeChallenge/objectCopy.js b/elementaryAlgo/JavaScriptCodeChallenge/objectCopy.js new file mode 100644 index 0000000..9e989e4 --- /dev/null +++ b/elementaryAlgo/JavaScriptCodeChallenge/objectCopy.js @@ -0,0 +1,34 @@ +const obj = { name: "rabo", description: "black and brain" }; +//shallow copy +let shallow = { ...obj }; +console.log(shallow); +//shallow copy and add properties +let shallowCopy = { ...obj, age: 0 }; +console.log(shallowCopy); +//shallow copy by Object.assign(); +let shallowAssign = Object.assign({}, obj, { country: "nigeria" }); +console.log(shallowAssign); +//stringify +let dee = { age: 67, email: "rab@gmail.com", desp: { num: 0 } }; +let fee = dee; +//console.log(fee.desp === dee.desp); +let copy = JSON.stringify(dee); +console.log(copy); +let copyByJSON = JSON.parse(copy); +//becasue of deep clone these two objects are not the same object +console.log(copyByJSON.desp === dee.desp); +//deep copy: JavaScript do not has a deep copy method but we can implement it +function deepCopy(obj) { + if (!obj) return obj; + let copyObj = {}; + for (let key in copyObj) { + if (typeof obj[key] !== "object" || Array.isArray(obj[key])) { + copyObj[key] = obj[key]; + } else { + copyObj[key] = deepCopy(obj[key]); + } + } + return copyObj; +} +let t = { name: "rabo", details: { col: "black" } }; +console.log(deepCopy(t)); diff --git a/elementaryAlgo/JavaScriptCodeChallenge/replaceThreeCenter.js b/elementaryAlgo/JavaScriptCodeChallenge/replaceThreeCenter.js new file mode 100644 index 0000000..a528842 --- /dev/null +++ b/elementaryAlgo/JavaScriptCodeChallenge/replaceThreeCenter.js @@ -0,0 +1,24 @@ +const a = [1, 2, 3, 4, 5]; +const b = [4, 0, 0, 0, 8]; + +const startPositionFor1stArray = a.length / 2 - 1; +const startPositionFor2ndArray = b.length / 2 - 1; +//console.log(startPositionFor1stArray, startPositionFor2ndArray); +console.log(a.splice(startPositionFor1stArray)); +a.splice( + startPositionFor1stArray, + 3, + ...b.slice(startPositionFor2ndArray, startPositionFor2ndArray + 3) +); + +const books = [ + { name: "Warcross", author: "Marie Lu" }, + { name: "The Hunger Games", author: "Suzanne Collins" }, + { name: "Harry Potter", author: "Joanne Rowling" }, +]; +const sortedObj = books.sort((a, b) => { + let book1 = a.author.split(" ")[1]; + let book2 = b.author.split(" ")[1]; + return book1 < book2 ? 1 : -1; +}); +console.log(sortedObj); diff --git a/elementaryAlgo/JavaScriptCodeChallenge/reverseEachWord.js b/elementaryAlgo/JavaScriptCodeChallenge/reverseEachWord.js new file mode 100644 index 0000000..3f38284 --- /dev/null +++ b/elementaryAlgo/JavaScriptCodeChallenge/reverseEachWord.js @@ -0,0 +1,6 @@ +const str = "JavaScript is awesome"; +const arrayReverseWords = str + .split(" ") + .map((word) => word.split("").reverse().join("")) + .join(" "); +console.log(arrayReverseWords); diff --git a/elementaryAlgo/JavaScriptCodeChallenge/reverseNum.js b/elementaryAlgo/JavaScriptCodeChallenge/reverseNum.js new file mode 100644 index 0000000..25600ad --- /dev/null +++ b/elementaryAlgo/JavaScriptCodeChallenge/reverseNum.js @@ -0,0 +1,4 @@ +let num = 3849; + +let numStr = String(num); ++numStr.split("").reverse().join(""); // 9483 \ No newline at end of file diff --git a/elementaryAlgo/JavaScriptCodeChallenge/threeWaysToLoopStr.js b/elementaryAlgo/JavaScriptCodeChallenge/threeWaysToLoopStr.js new file mode 100644 index 0000000..1ab295e --- /dev/null +++ b/elementaryAlgo/JavaScriptCodeChallenge/threeWaysToLoopStr.js @@ -0,0 +1,37 @@ +let str = "hello world"; +for (let i = 0; i < str.length; i++) { + console.log(str.charAt(i)); +} +for (let word in str) { + console.log(str[word]); +} +[...str].forEach((word) => console.log(word)); +for (let char of str) { + console.log(char); +} + +Math.abs(-5); // 5 +Math.floor(1.6); // 1 +Math.ceil(2.4); // 3 +Math.round(3.8); // 4 +Math.max(-4, 5, 6); // 6 +Math.min(-7, -2, 3); // -7 +Math.sqrt(64); // 8 +Math.pow(5, 3); // 125 +Math.trunc(-6.3); // -6 +const isInt = (value) => { + return value % 1 === 0; +}; +console.log(isInt(1)); +console.log(isInt(-6661)); +console.log(isInt(0)); +console.log(isInt(4.4)); +console.log(isInt(1.6)); +console.log(1 % 1); +console.log(3 % 1); +console.log(4 % 10); +console.log(50.4 % 1); +const randomNum = (start, end) => { + return Math.floor(Math.random() * (end - start)) + start; +}; +console.log(randomNum(1, 5)); diff --git a/elementaryAlgo/JavaScriptCodeChallenge/waysToCreateObject.js b/elementaryAlgo/JavaScriptCodeChallenge/waysToCreateObject.js new file mode 100644 index 0000000..8b0d0c4 --- /dev/null +++ b/elementaryAlgo/JavaScriptCodeChallenge/waysToCreateObject.js @@ -0,0 +1,111 @@ +let obj = { name: "random", email: "random@example.com" }; +const result = Object.create(obj); +result.age = 800; +result.speak = function () { + return `My name is ${this.name} and I am ${this.age} years old.`; +}; +console.log(result); +console.log(result.name); +console.log(result.age); +console.log(result.hasOwnProperty("name")); +console.log(result.hasOwnProperty("age")); +console.log(result.hasOwnProperty("speak")); +console.log(result.speak()); +let protoRabbit = { + speak(line) { + return `The ${this.type} rabbit says '${line}'`; + }, +}; +let killerRabbit = Object.create(protoRabbit); +killerRabbit.type = "killer"; +console.log(killerRabbit.hasOwnProperty("type")); +console.log(killerRabbit.speak("SKREEEE!")); +// → The killer rabbit says 'SKREEEE! +function factoryFunc(key, value) { + return { + key, + value, + }; +} +let factory = new factoryFunc("age", 78); +console.log(factory.value); +console.log(factory.hasOwnProperty("value")); +function facFunc(key, value) { + this[key] = value; +} +const fa = new facFunc("name", 800); +console.log(fa.name); +class Constr { + constructor(name, age = 0) { + this.name = name; + this.age = age; + } + getName() { + return this.name; + } +} +const ob = { name: "hello" }; +for (let key in ob) { + if (ob.hasOwnProperty(key)) { + console.log(key); + } +} + +for (let key of Object.keys(ob)) { + if (ob.hasOwnProperty(key)) { + console.log(key); + } +} +Object.keys(ob).forEach((key) => { + if (ob.hasOwnProperty(key)) { + console.log(key); + } +}); +const countKey = (obj) => { + let count = 0; + Object.keys(obj).forEach((key) => { + if (obj.hasOwnProperty(key)) { + count += 1; + } + }); + return count; +}; +console.log(countKey(ob)); +console.log(Object.create(obj).toString()); +console.log(Object.create(null)); +let valuePairs = [ + ["0", 0], + ["1", 1], + ["2", 2], +]; +let objPair = Object.fromEntries(valuePairs); +console.log(objPair); +let map = new Map([ + ["age", 80], + ["name", "rabo"], +]); +let mapPair = Object.fromEntries(map); +console.log(mapPair); +for (let [key, value] of map) { + console.log(key, value); +} +console.log(new Set([8, 9, 0])); +// let obj1 = {age: 56}, +// obj2 = {col: 'red'}; +// obj1.setPrototypeOf(obj2) +const obj1 = { a: 1 }; +const obj2 = { b: 2 }; +Object.setPrototypeOf(obj2, obj1); +//obj2.__proto__ = obj1; +console.log(obj1.isPrototypeOf(obj2)); +let objWithGetSet = {}; +let o = Object.defineProperty(objWithGetSet, "data", { + data: 0, + get() { + return this.value; + }, + set(value) { + this.value = value; + }, +}); +o.data = 90; diff --git a/elementaryAlgo/addTwoNumber.js b/elementaryAlgo/addTwoNumber.js new file mode 100644 index 0000000..f5bcfd8 --- /dev/null +++ b/elementaryAlgo/addTwoNumber.js @@ -0,0 +1,4 @@ +const addTwoNumber = (num1, num2) => { + return num1 + num2; +}; +console.log(addTwoNumber(2, 4)); diff --git a/elementaryAlgo/alvin/alternateCap.js b/elementaryAlgo/alvin/alternateCap.js new file mode 100644 index 0000000..a9bf474 --- /dev/null +++ b/elementaryAlgo/alvin/alternateCap.js @@ -0,0 +1,17 @@ +// Write a function `alternatingCaps` that accepts a sentence string as an argument. The function should +// return the sentence where words alternate between lowercase and uppercase. +const alternatingCaps = (words) => { + let result = ""; + let arraySplit = words.split(" "); + for (let i = 0; i < arraySplit.length; i++) { + let word = arraySplit[i]; + if (i % 2 === 0) { + result += word.toLowerCase() + " "; + } else { + result += word.toUpperCase() + " "; + } + } + return result; +}; +console.log(alternatingCaps("take them to school")); // 'take THEM to SCHOOL' +console.log(alternatingCaps("What did ThEy EAT before?")); // 'what DID they EAT before?' diff --git a/elementaryAlgo/alvin/bleepVowels.js b/elementaryAlgo/alvin/bleepVowels.js new file mode 100644 index 0000000..e2c618d --- /dev/null +++ b/elementaryAlgo/alvin/bleepVowels.js @@ -0,0 +1,19 @@ +// Write a function `bleepVowels` that accepts a string as an argument. The function should return +// a new string where all vowels are replaced with `*`s. Vowels are the letters a, e, i, o, u. +function bleepVowels(str) { + let array = ["a", "e", "i", "o", "u"]; + let result = ""; + for (let i = 0; i < str.length; i++) { + let char = str[i]; + if (array.indexOf(char) > -1) { + result += "*"; + } else { + result += char; + } + } + return result; +} +console.log(bleepVowels("skateboard")); // 'sk*t*b**rd' +console.log(bleepVowels("slipper")); // 'sl*pp*r' +console.log(bleepVowels("range")); // 'r*ng*' +console.log(bleepVowels("brisk morning")); // 'br*sk m*rn*ng' diff --git a/elementaryAlgo/alvin/chooseDivisible.js b/elementaryAlgo/alvin/chooseDivisible.js new file mode 100644 index 0000000..fc5b1d5 --- /dev/null +++ b/elementaryAlgo/alvin/chooseDivisible.js @@ -0,0 +1,16 @@ +// Write a function `chooseDivisibles(numbers, target)` that accepts an array of numbers and a +// target number as arguments. The function should return an array containing elements of the original +// array that are divisible by the target. +const chooseDivisibles = (numbers, target) => { + let result = []; + for (let i = 0; i < numbers.length; i++) { + let num = numbers[i]; + if (num % target === 0) { + result.push(num); + } + } + return result; +}; +console.log(chooseDivisibles([40, 7, 22, 20, 24], 4)); // [40, 20, 24] +console.log(chooseDivisibles([9, 33, 8, 17], 3)); // [9, 33] +console.log(chooseDivisibles([4, 25, 1000], 10)); // [1000] diff --git a/elementaryAlgo/alvin/combinations.js b/elementaryAlgo/alvin/combinations.js new file mode 100644 index 0000000..bf94843 --- /dev/null +++ b/elementaryAlgo/alvin/combinations.js @@ -0,0 +1,16 @@ +const combinations = (array) => { + if (array.length === 0) return [[]]; + let firstElem = array[0]; + let withFirst = array.slice(1); + let combinationWithFirstElem = []; + let combinationWithoutFirstElem = combinations(withFirst); + combinationWithoutFirstElem.forEach((arr) => { + let WithFirstElem = [...arr, firstElem]; + combinationWithFirstElem.push(WithFirstElem); + }); + return [...combinationWithFirstElem, ...combinationWithoutFirstElem]; +}; +console.log(combinations(["a", "b", "c"])); +console.log(combinations(["a", "b"])); +//Time : O(2^n) +//Space : O(n * n) diff --git a/elementaryAlgo/alvin/commonElement.js b/elementaryAlgo/alvin/commonElement.js new file mode 100644 index 0000000..9388309 --- /dev/null +++ b/elementaryAlgo/alvin/commonElement.js @@ -0,0 +1,21 @@ +// Write a function `commonElements` that accepts two arrays as arguments. The function should return +// a new array containing the elements that are found in both of the input arrays. The order of +// the elements in the output array doesn't matter as long as the function returns the correct elements. +const commonElements = (array1, array2) => { + let result = []; + let set1 = new Set(array1); + let set2 = new Set(array2); + for (let elem of set1) { + if (set2.has(elem)) { + result.push(elem); + } + } + return result; +}; +let arr1 = ["a", "c", "d", "b"]; +let arr2 = ["b", "a", "y"]; +console.log(commonElements(arr1, arr2)); // ['a', 'b'] + +let arr3 = [4, 7]; +let arr4 = [32, 7, 1, 4]; +console.log(commonElements(arr3, arr4)); // [4, 7] diff --git a/elementaryAlgo/alvin/divisors.js b/elementaryAlgo/alvin/divisors.js new file mode 100644 index 0000000..7ffe447 --- /dev/null +++ b/elementaryAlgo/alvin/divisors.js @@ -0,0 +1,15 @@ +// Write a function `divisors` that accepts a number as an argument. The function should return an +// array containing all positive numbers that can divide into the argument. +function divisors(num) { + let result = []; + for (let i = 1; i <= num; i++) { + let eachNum = i; + if (num % eachNum === 0) { + result.push(eachNum); + } + } + return result; +} +console.log(divisors(15)); // [1, 3, 5, 15] +console.log(divisors(7)); // [1, 7] +console.log(divisors(24)); // [1, 2, 3, 4, 6, 8, 12, 24] diff --git a/elementaryAlgo/alvin/filterLongWords.js b/elementaryAlgo/alvin/filterLongWords.js new file mode 100644 index 0000000..99b097a --- /dev/null +++ b/elementaryAlgo/alvin/filterLongWords.js @@ -0,0 +1,17 @@ +// Write a function `filterLongWords` that accepts an array of strings as an argument. The function +// should return a new array containing only the strings that are less than 5 characters long. +function filterLongWords(array) { + let result = []; + for (let i = 0; i < array.length; i++) { + let word = array[i]; + if (word.length < 5) { + result.push(word); + } + } + return result; +} +console.log(filterLongWords(["kale", "cat", "retro", "axe", "heirloom"])); +// ['kale', 'cat', 'axe'] + +console.log(filterLongWords(["disrupt", "pour", "trade", "pic"])); +// ['pour', 'pic'] diff --git a/elementaryAlgo/alvin/ifelse.js b/elementaryAlgo/alvin/ifelse.js new file mode 100644 index 0000000..36f7f7a --- /dev/null +++ b/elementaryAlgo/alvin/ifelse.js @@ -0,0 +1,14 @@ +let number = 10; +if (number > 0) { + console.log("Is greater than zero"); +} +if (number % 10 === 0) { + console.log("Is even number"); +} else { + console.log("hello"); +} + +let str = "now I love you"; +for (let i = str.length - 1; i >= 0; i--) { + console.log(str[i]); +} diff --git a/elementaryAlgo/alvin/lengthiestWord.js b/elementaryAlgo/alvin/lengthiestWord.js new file mode 100644 index 0000000..af76bfc --- /dev/null +++ b/elementaryAlgo/alvin/lengthiestWord.js @@ -0,0 +1,18 @@ +// Write a function `lengthiestWord` that accepts a sentence string as an argument. The function should +// return the longest word of the sentence. If there is a tie, return the word that appears later +// in the sentence. +const lengthiestWord = (words) => { + let arrayWord = words.split(" "); + let lengthiest = arrayWord[0]; + for (let i = 1; i < arrayWord.length; i++) { + let word = arrayWord[i]; + if (lengthiest.length <= word.length) { + lengthiest = word; + } + } + return lengthiest; +}; +console.log(lengthiestWord("I am pretty hungry")); // 'hungry' +console.log(lengthiestWord("we should think outside of the box")); // 'outside' +console.log(lengthiestWord("down the rabbit hole")); // 'rabbit' +console.log(lengthiestWord("simmer down")); // 'simmer' diff --git a/elementaryAlgo/alvin/makeAcronyms.js b/elementaryAlgo/alvin/makeAcronyms.js new file mode 100644 index 0000000..2915a74 --- /dev/null +++ b/elementaryAlgo/alvin/makeAcronyms.js @@ -0,0 +1,15 @@ +// Write a function `makeAcronym` that accepts a sentence string as an argument. The function should +// return a string containing the first character of each word in the sentence. +const makeAcronym = (words) => { + let arrayWord = words.split(" "); + let result = ""; + for (let i = 0; i < arrayWord.length; i++) { + let word = arrayWord[i][0]; + result += word.toUpperCase(); + } + return result; +}; +console.log(makeAcronym("New York")); // NY +console.log(makeAcronym("same stuff different day")); // SSDD +console.log(makeAcronym("Laugh out loud")); // LOL +console.log(makeAcronym("don't over think stuff")); // DOTS diff --git a/elementaryAlgo/alvin/makeMatrix.js b/elementaryAlgo/alvin/makeMatrix.js new file mode 100644 index 0000000..195d208 --- /dev/null +++ b/elementaryAlgo/alvin/makeMatrix.js @@ -0,0 +1,37 @@ +// Write a function `makeMatrix(m, n, value)` that accepts three arguments. The function should return +// a 2-dimensional array of height `m` and width `n` that contains the `value` as every element. +const makeMatrix = (m, n, value) => { + let matrix = []; + for (let i = 0; i < m; i++) { + let row = []; + for (let j = 0; j < n; j++) { + row.push(value); + } + matrix.push(row); + } + return matrix; +}; +// const makeMatrix = (m, n, value) => { +// let matrix = Array.from(Array(m), () => Array(n).fill(value)); +// return matrix +// }; +console.log(makeMatrix(3, 5, null)); +// [ +// [ null, null, null, null, null ], +// [ null, null, null, null, null ], +// [ null, null, null, null, null ] +// ] + +console.log(makeMatrix(4, 2, "x")); +// [ +// [ 'x', 'x' ], +// [ 'x', 'x' ], +// [ 'x', 'x' ], +// [ 'x', 'x' ] +// ] + +console.log(makeMatrix(2, 2, 0)); +// [ +// [ 0, 0 ], +// [ 0, 0 ] +// ] diff --git a/elementaryAlgo/alvin/maximum.js b/elementaryAlgo/alvin/maximum.js new file mode 100644 index 0000000..e7052fd --- /dev/null +++ b/elementaryAlgo/alvin/maximum.js @@ -0,0 +1,14 @@ +// Write a function `maximum` that accepts an array of numbers as an argument. The function should +// return the largest number of the array. If the array is empty, then the function should return null. +const maximum = (array) => { + if (array.length === 0) return null; + let max = array[0]; + for (let i = 1; i < array.length; i++) { + let elem = array[i]; + max = Math.max(max, elem); + } + return max; +}; +console.log(maximum([5, 6, 3, 7])); // 7 +console.log(maximum([17, 15, 19, 11, 2])); // 19 +console.log(maximum([])); // null diff --git a/elementaryAlgo/alvin/nested.js b/elementaryAlgo/alvin/nested.js new file mode 100644 index 0000000..32f2f95 --- /dev/null +++ b/elementaryAlgo/alvin/nested.js @@ -0,0 +1,46 @@ +// snippet 1 +for (let i = 1; i <= 4; i++) { + for (let j = 1; j <= 3; j++) { + console.log(i, j); + } +} + +// snippet 2 +for (let n = 0; n < 2; n++) { + console.log("n=" + n); + for (let m = 0; m < 5; m++) { + console.log(" m=" + m); + } + console.log("n=" + n); +} + +// snippet 3 +let friends = ["philip", "abby", "phelipe", "simcha"]; + +for (let i = 0; i < friends.length; i++) { + for (let j = 0; j < friends.length; j++) { + console.log(friends[i], friends[j]); + } +} + +// snippet 4 +let locations = ["flatbush", "williamsburg", "bushwick", "greenpoint"]; + +for (let i = 0; i < locations.length; i++) { + for (let j = i + 1; j < locations.length; j++) { + console.log(locations[i], locations[j]); + } +} + +// snippet 5 +let colors = ["red", "purple", "orange"]; + +for (let i = 0; i < colors.length; i++) { + let colorStr = colors[i]; + console.log(colorStr); + + for (let j = 0; j < colorStr.length; j++) { + let char = colorStr[j]; + console.log(char); + } +} diff --git a/elementaryAlgo/alvin/numOdd.js b/elementaryAlgo/alvin/numOdd.js new file mode 100644 index 0000000..2b8f9df --- /dev/null +++ b/elementaryAlgo/alvin/numOdd.js @@ -0,0 +1,13 @@ +// Write a function `numOdds` that accepts an array of numbers as an argument. The function should +// return a number representing the count of odd elements in the array. +function numOdds(array) { + let count = 0; + for (let i = 0; i < array.length; i++) { + let num = array[i]; + if (num % 2 === 1) count++; + } + return count; +} +console.log(numOdds([4, 7, 2, 5, 9])); // 3 +console.log(numOdds([11, 31, 58, 99, 21, 60])); // 4 +console.log(numOdds([100, 40, 4])); // 0 diff --git a/elementaryAlgo/alvin/number.js b/elementaryAlgo/alvin/number.js new file mode 100644 index 0000000..ede2738 --- /dev/null +++ b/elementaryAlgo/alvin/number.js @@ -0,0 +1,14 @@ +console.log(2 > 5); +console.log(100 > 5); +console.log(5 > 78); +console.log(45 === 45); +console.log(3 >= 56); +console.log(3 <= 57); +console.log(4 == "4"); +console.log(5 == "5"); +console.log("a" === "a"); +console.log("b" === "bc"); +console.log("c" === ""); +console.log(40 % 10); +console.log(100 % 10); +console.log(101 % 10); diff --git a/elementaryAlgo/alvin/numberRange.js b/elementaryAlgo/alvin/numberRange.js new file mode 100644 index 0000000..f7850a3 --- /dev/null +++ b/elementaryAlgo/alvin/numberRange.js @@ -0,0 +1,13 @@ +// Write a function `numberRange(min, max, step)` that accepts three numbers as arguments, `min`, +// `max`, and `step`. The function should return all numbers between `min` and `max` at `step` intervals. +// `min` and `max` are inclusive. +const numberRange = (min, max, step) => { + let result = []; + for (let i = min; i <= max; i += step) { + result.push(i); + } + return result; +}; +console.log(numberRange(10, 40, 5)); // [10, 15, 20, 25, 30, 35, 40] +console.log(numberRange(14, 24, 3)); // [14, 17, 20, 23] +console.log(numberRange(8, 35, 6)); // [8, 14, 20, 26, 32] diff --git a/elementaryAlgo/alvin/pairPrint.js b/elementaryAlgo/alvin/pairPrint.js new file mode 100644 index 0000000..96f9ead --- /dev/null +++ b/elementaryAlgo/alvin/pairPrint.js @@ -0,0 +1,25 @@ +function pairPrint(arr) { + for (let i = 0; i < arr.length; i++) { + for (let j = i + 1; j < arr.length; j++) { + console.log(arr[i], arr[j]); + } + } +} +// Write a function `pairPrint` that accepts an array as an argument. The function should print +// all unique pairs of elements in the array. The function doesn't need to return any value. It +// should just print to the terminal. + +pairPrint(["artichoke", "broccoli", "carrot", "daikon"]); +// prints +// artichoke - broccoli +// artichoke - carrot +// artichoke - daikon +// broccoli - carrot +// broccoli - daikon +// carrot - daikon + +//pairPrint(["apple", "banana", "clementine"]); +// prints +// apple - banana +// apple - clementine +// banana - clementine diff --git a/elementaryAlgo/alvin/permutations.js b/elementaryAlgo/alvin/permutations.js new file mode 100644 index 0000000..a218ff3 --- /dev/null +++ b/elementaryAlgo/alvin/permutations.js @@ -0,0 +1,22 @@ +const permutations = (array) => { + if (array.length === 0) return [[]]; + let firstElem = array[0]; + let rest = array.slice(1); + let permutationsWithoutFirst = permutations(rest); + let allPermutation = []; + permutationsWithoutFirst.forEach((perm) => { + //inserting firstElem elements in all possible positions + for (let i = 0; i <= perm.length; i++) { + let permutationWithFirstElem = [ + ...perm.slice(0, i), + firstElem, + ...perm.slice(i), + ]; + allPermutation.push(permutationWithFirstElem); + } + }); + return allPermutation; +}; +console.log(permutations(["a", "b", "c"])); +//Time: O(n!) +//Space: O(n^2) diff --git a/elementaryAlgo/alvin/print2d.js b/elementaryAlgo/alvin/print2d.js new file mode 100644 index 0000000..43e2492 --- /dev/null +++ b/elementaryAlgo/alvin/print2d.js @@ -0,0 +1,36 @@ +// Write a function `print2d` that accepts a two-dimensional array as an argument. The function +// should print all inner elements of the array. +const print2d = (array) => { + for (let i = 0; i < array.length; i++) { + let innerElem = array[i]; + for (let j = 0; j < innerElem.length; j++) { + console.log(innerElem[j]); + } + } +}; +let array1 = [ + ["a", "b", "c", "d"], + ["e", "f"], + ["g", "h", "i"], +]; +print2d(array1); +// prints +// a +// b +// c +// d +// e +// f +// g +// h +// i + +let array2 = [[9, 3, 4], [11], [42, 100]]; +print2d(array2); +// prints +// 9 +// 3 +// 4 +// 11 +// 42 +// 100 diff --git a/elementaryAlgo/alvin/printCombination.js b/elementaryAlgo/alvin/printCombination.js new file mode 100644 index 0000000..32505de --- /dev/null +++ b/elementaryAlgo/alvin/printCombination.js @@ -0,0 +1,32 @@ +// Write a function `printCombinations`that accepts two arrays as arguments. The function should +// print all combinations of the elements generated by taking an element from the first array and +// and an element from the second array. The function doesn't need to return any value. It +// should just print to the terminal. +function printCombinations(array1, array2) { + for (let i = 0; i < array1.length; i++) { + const element1 = array1[i]; + for (let j = 0; j < array2.length; j++) { + let element2 = array2[j]; + console.log(element1, element2); + } + } +} + +let colors = ["gray", "cream", "cyan"]; +let clothes = ["shirt", "flannel"]; + +printCombinations(colors, clothes); +// prints +// gray shirt +// gray flannel +// cream shirt +// cream flannel +// cyan shirt +// cyan flannel + +//printCombinations(["hot", "cold"], ["soup", "tea"]); +// prints +// hot soup +// hot tea +// cold soup +// cold tea diff --git a/elementaryAlgo/alvin/recursionArray.js b/elementaryAlgo/alvin/recursionArray.js new file mode 100644 index 0000000..26273b9 --- /dev/null +++ b/elementaryAlgo/alvin/recursionArray.js @@ -0,0 +1,20 @@ +//Given an array of integers, write a function that return the sum all of it element using recursion +const sum = (array) => { + if (array.length === 0) return 0; + let rest = array.slice(1); + return array[0] + sum(rest); +}; +console.log(sum([2, 5, 6, 8, 9])); +//Time: O(n^2) +//Space: O(n) +// can improve our space complexity like this +const sumImprove = (array) => { + return _sum(array, 0); +}; +const _sum = (array, idx) => { + if (array.length === idx) return 0; + return array[idx] + _sum(array, idx + 1); +}; +console.log(sumImprove([2, 5, 6, 8, 9])); +//Time: O(n) +//Space: O(n) diff --git a/elementaryAlgo/alvin/removeFirstVowel.js b/elementaryAlgo/alvin/removeFirstVowel.js new file mode 100644 index 0000000..e10a3fc --- /dev/null +++ b/elementaryAlgo/alvin/removeFirstVowel.js @@ -0,0 +1,18 @@ +// Write a function `removeFirstVowel` that accepts a string as an argument. The function should return +// the string with it's first vowel removed. +const removeFirstVowel = (words) => { + let vowels = ["a", "e", "i", "o", "u"]; + for (let i = 0; i < words.length; i++) { + let word = words[i]; + if (vowels.includes(word)) { + let copy = words.split(""); + copy.splice(i, 1); + return copy.join(""); + } + } + return words; +}; +console.log(removeFirstVowel("volcano")); // 'vlcano' +console.log(removeFirstVowel("celery")); // 'clery' +console.log(removeFirstVowel("juice")); // 'jice' +console.log(removeFirstVowel("ghshsh")); diff --git a/elementaryAlgo/alvin/removeShortWords.js b/elementaryAlgo/alvin/removeShortWords.js new file mode 100644 index 0000000..1218a0d --- /dev/null +++ b/elementaryAlgo/alvin/removeShortWords.js @@ -0,0 +1,15 @@ +// Write a function `removeShortWords` that accepts a sentence string as an argument. The function +// should return a new sentence where all of the words shorter than 4 characters are removed. +const removeShortWords = (words) => { + let result = ""; + let arrayWords = words.split(" "); + for (let i = 0; i < arrayWords.length; i++) { + let word = arrayWords[i]; + if (word.length < 4) continue; + else result += word + " "; + } + return result; +}; +console.log(removeShortWords("knock on the door will you")); // 'knock door will' +console.log(removeShortWords("a terrible plan")); // 'terrible plan' +console.log(removeShortWords("run faster that way")); // 'faster that' diff --git a/elementaryAlgo/alvin/reverseArray.js b/elementaryAlgo/alvin/reverseArray.js new file mode 100644 index 0000000..9cb3311 --- /dev/null +++ b/elementaryAlgo/alvin/reverseArray.js @@ -0,0 +1,12 @@ +// Write a function `reverseArray` that accepts an array as an argument. The function should return a +// array containing the elements of the original array in reverse order. +const reverseArray = (array) => { + let result = []; + for (let i = array.length - 1; i >= 0; i--) { + let element = array[i]; + result.push(element); + } + return result; +}; +console.log(reverseArray(["zero", "one", "two", "three"])); // ['three', 'two', 'one', 'zero'] +console.log(reverseArray([7, 1, 8])); // [8, 1, 7] diff --git a/elementaryAlgo/alvin/smallestNum.js b/elementaryAlgo/alvin/smallestNum.js new file mode 100644 index 0000000..f3de8e4 --- /dev/null +++ b/elementaryAlgo/alvin/smallestNum.js @@ -0,0 +1,12 @@ +const smallNum = (nums) => { + if (nums.length === 0) return null; + let smallest = nums[0]; + for (let i = 1; i < nums.length; i++) { + let num = nums[i]; + smallest = Math.min(num, smallest); + } + return smallest; +}; +console.log(smallNum([3, 5, 8, 1, 9])); +console.log(smallNum([])); +console.log(smallNum([3, 5, 2, 4])); diff --git a/elementaryAlgo/alvin/stayPositive.js b/elementaryAlgo/alvin/stayPositive.js new file mode 100644 index 0000000..e3411c6 --- /dev/null +++ b/elementaryAlgo/alvin/stayPositive.js @@ -0,0 +1,15 @@ +// Write a function `stayPositive` that accepts an array of numbers as an argument. The function should +// return an array containing only the positive numbers. +function stayPositive(array) { + let result = []; + for (let i = 0; i < array.length; i++) { + let num = array[i]; + if (num > 0) { + result.push(num); + } + } + return result; +} +console.log(stayPositive([10, -4, 3, 6])); // [10, 3, 6] +console.log(stayPositive([-5, 11, -40, 30.3, -2])); // [11, 30.3] +console.log(stayPositive([-11, -30])); // [] diff --git a/elementaryAlgo/alvin/string.js b/elementaryAlgo/alvin/string.js new file mode 100644 index 0000000..957a6a6 --- /dev/null +++ b/elementaryAlgo/alvin/string.js @@ -0,0 +1,58 @@ +// console.log("promenade"[3]); +// console.log("tiger"[1]); +// console.log("wheel".length); +// console.log("wheel".length - 1); +// console.log("noMAD".toUpperCase()); +// console.log("hey programmers"[2] === "y"); + +// console.log("volleyball".length > 20); +// console.log("treasure".indexOf("r")); +// console.log("treasure".indexOf("e")); +// console.log("web"[5]); +// console.log("red".indexOf("x")); +// console.log("red".indexOf("R")); +// let str = "hello programmers"; +// console.log(str.indexOf("help") > -1); +// console.log(str.indexOf("pro") > -1); +// let word = "suspension bridge"; +// console.log(word[4]); +// console.log(word.length > 4 && word[0]); +// console.log(word.length > 5 && word[0] === "d"); +// console.log(word.length > 5 && word[0] === "s"); +// console.log(word.indexOf("o") > -1); +// console.log(word.indexOf("z") > -1); + +// let str = "foggy"; +// console.log(str[2 + 1]); +// console.log(str[str.length - 1]); +// str = " day"; +// console.log(str); +// console.log(str.length); +// console.log(str.indexOf("ogg")); +let phrase = "that's all folks"; +console.log(phrase[phrase.length]); +console.log(phrase[phrase.length - 1]); +console.log(phrase[phrase.length - 2]); + +const i = 9; +const char = phrase[i]; +console.log(char); +console.log(phrase.indexOf(char)); +console.log(phrase.slice(2, 8)); + +console.log("abcdefg".slice(1, 3)); +console.log("abcdefg".slice(2)); +console.log("abcdefg".slice(4)); +console.log("abcdefg".slice(2, -1)); +console.log("abcdefg".slice(2, -2)); +let string = `MIICWwIBAAKBgGEdLjFEFbegPZ2AwJWkalksXr7PzWL7wIc7pOFZxXwYPWt +QxvANyceCwpkqbPLsfEx7nqxAris2hYOdeN1OTFqvTyNmVuzbUPcXShn6ZoDCB30voHkeu4F3cUw5 +RQEUDdLscSnv4HMxHam5qgl6vXoumVNHbjyKA5UtAnfjAgMBAAECgYAmjEyvpZTxRJvwjxDi1VaZevF +I0Hd4WPH9PAGgqdnH84vGXnAGFj1WikqKYcqKMQW2kdjAsWwH9D9FfrkIcDDHdZ9XuGSGkFzWtOwajWMQl7 +qNV1hZ288gdpIQQMOTLDgauZY6pw1cV7h4v316qJB8knQGoBNpJCfTYQJBAKV1ctsJq0Zg4QumD2hyODepP3L +fLeaQsERLqVAWeuOuTY5mK5gIwsSqvcSVfY7Ze1FWIsApNFRv67azKcJPwsCQQCNlyApZFJEVNY70Er7Uu5NL9t4C +YJJC9uVVkoEHEY6d7sVslqa0vP2q0zXx9YedbMBvQjxXIbY0waXUy63FvoBGJAkB3OTJWUjVgzDY1Br5wu2Yu59NjKVKLW +zCsu1gaCNBfhVDX7SyIyC9EYKRfUAoQxwsmPWPyQ9QVG4WKcPZJAkBRheAotPCBE2RLHHfvpiStnMhX0UXdVyaJp5tcZ6wYV61oh +yBvCOkYhUxBJzeIGrVZcvLZSLeUzXoqRPpxQxAkEAkdCZXF0gHahpZgF5y0wWcqf9ECRT1E4Hv8bk3Mf0Exp2aW34JeI6I7Xqd1NV4I +9H7prQ8m3y39lFwWO8PmQ`; +console.log(string.indexOf("HEY")); diff --git a/elementaryAlgo/alvin/stringToLength.js b/elementaryAlgo/alvin/stringToLength.js new file mode 100644 index 0000000..70cf054 --- /dev/null +++ b/elementaryAlgo/alvin/stringToLength.js @@ -0,0 +1,15 @@ +// Write a function `stringsToLengths` that accepts an array of strings as an argument. The function +// should return a new array containing the lengths of the elements of the original array. +function stringsToLengths(array) { + let result = []; + for (let i = 0; i < array.length; i++) { + let word = array[i]; + result.push(word.length); + } + return result; +} +console.log(stringsToLengths(["belly", "echo", "irony", "pickled"])); +// [5, 4, 5, 7] + +console.log(stringsToLengths(["on", "off", "handmade"])); +// [2, 3, 8] diff --git a/elementaryAlgo/alvin/total.js b/elementaryAlgo/alvin/total.js new file mode 100644 index 0000000..1030568 --- /dev/null +++ b/elementaryAlgo/alvin/total.js @@ -0,0 +1,22 @@ +// Write a function `total` that accepts an array of numbers as an argument. The function should return +// the total sum of all elements of the array. + +function total(array) { + let sum = 0; + for (let i = 0; i < array.length; i++) { + sum += array[i]; + } + return sum; +} +console.log(total([3, 2, 8])); // 13 +console.log(total([-5, 7, 4, 6])); // 12 +console.log(total([7])); // 7 +console.log(total([])); // 0 + +let obj = { + name: "right", + number: 3, +}; + +if (key in obj) { +} diff --git a/elementaryAlgo/alvin/totalProducts.js b/elementaryAlgo/alvin/totalProducts.js new file mode 100644 index 0000000..d9f25eb --- /dev/null +++ b/elementaryAlgo/alvin/totalProducts.js @@ -0,0 +1,24 @@ +// Write a function `totalProduct(array)` that accepts a 2D array of numbers. The function should return +// the total product of all numbers in the array. +const totalProduct = (array) => { + let totalProduct = 1; + for (let i = 0; i < array.length; i++) { + let product = array[i]; + for (let j = 0; j < product.length; j++) { + totalProduct *= product[j]; + } + } + return totalProduct; +}; +let array1 = [ + [3, 5, 2], + [6, 2], +]; +console.log(totalProduct(array1)); // 360 + +let array2 = [ + [4, 6], + [2, 3], + [1, 2], +]; +console.log(totalProduct(array2)); // 288 diff --git a/elementaryAlgo/alvin/twoSum.js b/elementaryAlgo/alvin/twoSum.js new file mode 100644 index 0000000..c8dc9e8 --- /dev/null +++ b/elementaryAlgo/alvin/twoSum.js @@ -0,0 +1,15 @@ +// Write a function `twoSum(numbers, target)` that accepts an array of numbers and a target number +// as an argument. The function should return a boolean indicating whether or not there exists a pair +// of distinct elements in the array that sum to the target. +function twoSum(numbers, target) { + for (let i = 0; i < numbers.length; i++) { + for (let j = i + 1; j < numbers.length; j++) { + if (numbers[i] + numbers[j] === target) return true; + } + } + return false; +} +console.log(twoSum([2, 3, 5, 9], 7)); // true +console.log(twoSum([2, 3, 5, 9], 4)); // false +console.log(twoSum([6, 3, 4], 10)); // true +console.log(twoSum([6, 5, 1], 10)); // false diff --git a/elementaryAlgo/alvin/twoSumPairs.js b/elementaryAlgo/alvin/twoSumPairs.js new file mode 100644 index 0000000..653a20e --- /dev/null +++ b/elementaryAlgo/alvin/twoSumPairs.js @@ -0,0 +1,18 @@ +// Write a function `twoSumPairs(numbers, target)` that accepts an array of numbers and a target number +// as arguments. The function should return a 2D array containing all unique pairs of elements that +// sum to the target. +const twoSumPairs = (numbers, target) => { + let result = []; + for (let i = 0; i < numbers.length; i++) { + for (let j = i + 1; j < numbers.length; j++) { + if (numbers[i] + numbers[j] === target) { + result.push([numbers[i], numbers[j]]); + } + } + } + return result; +}; +console.log(twoSumPairs([2, 3, 4, 6, 5], 8)); // [ [2, 6], [3, 5] ] +console.log(twoSumPairs([10, 7, 4, 5, 2], 12)); // [ [10, 2], [7, 5] ] +console.log(twoSumPairs([3, 9, 8], 11)); // [ [3, 8] ] +console.log(twoSumPairs([3, 9, 8], 10)); // [ ] diff --git a/elementaryAlgo/alvin/wordCount.js b/elementaryAlgo/alvin/wordCount.js new file mode 100644 index 0000000..244fd05 --- /dev/null +++ b/elementaryAlgo/alvin/wordCount.js @@ -0,0 +1,15 @@ +// Write a function `wordCount(sentence, targetWords)` that accepts a sentence string and an array of +// `targetWords`. The function should return a count of the number of words of the sentence that are +// in `targetWords`. +const wordCount = (sentence, targetWords) => { + let count = 0; + for (let i = 0; i < targetWords.length; i++) { + if (sentence.indexOf(targetWords[i]) > -1) { + count += 1; + } + } + return count; +}; +console.log(wordCount("open the window please", ["please", "open", "sorry"])); // 2 +console.log(wordCount("drive to the cinema", ["the", "driver"])); // 1 +console.log(wordCount("can I have that can", ["can", "I"])); // 3 diff --git a/elementaryAlgo/alvin/yourAverageFunc.js b/elementaryAlgo/alvin/yourAverageFunc.js new file mode 100644 index 0000000..cc4e6e3 --- /dev/null +++ b/elementaryAlgo/alvin/yourAverageFunc.js @@ -0,0 +1,16 @@ +// Write a function `yourAverageFunction` that accepts an array of numbers as an argument. The +// function should return the average of all elements of the array. If the input array is empty, +// then the function should return null. +const yourAverageFunction = (array) => { + if (array.length === 0) return null; + let sum = 0; + for (let i = 0; i < array.length; i++) { + let num = array[i]; + sum += num; + } + return sum / array.length; +}; +console.log(yourAverageFunction([5, 2, 7, 24])); // 9.5 +console.log(yourAverageFunction([100, 6])); // 53 +console.log(yourAverageFunction([31, 32, 40, 12, 33])); // 29.6 +console.log(yourAverageFunction([])); // null diff --git a/elementaryAlgo/alvin/zipper.js b/elementaryAlgo/alvin/zipper.js new file mode 100644 index 0000000..3537a23 --- /dev/null +++ b/elementaryAlgo/alvin/zipper.js @@ -0,0 +1,41 @@ +// Write a function `zipper` that accepts two arrays as arguments. The function should return a 2D +// array containing pairs of elements at the same indices. You can assume that the arrays have the +// same length. +const zipper = (array1, array2) => { + let result = []; + for (let i = 0; i < array1.length; i++) { + let elem1 = array1[i]; + let elem2 = array2[i]; + result.push([elem1, elem2]); + } + return result; +}; +// const zipper = (array1, array2) => { +// let result = [] +// for (let i = 0; i < array1.length; i++) { +// for (let j = 0; j < array2.length; j++) { +// if(i === j){ +// result.push([array1[i], array2[j]]) +// } +// } +// } +// return result +// }; +let array1 = ["a", "b", "c", "d"]; +let array2 = [-1, -2, -3, -4]; +console.log(zipper(array1, array2)); +// [ +// ['a', -1], +// ['b', -2], +// ['c', -3], +// ['d', -4], +// ] + +let array3 = ["whisper", "talk", "shout"]; +let array4 = ["quiet", "normal", "loud"]; +console.log(zipper(array3, array4)); +// [ +// ['whisper', 'quiet'], +// ['talk', 'normal'], +// ['shout', 'loud'], +// ] diff --git a/elementaryAlgo/areaOfTriangle.js b/elementaryAlgo/areaOfTriangle.js new file mode 100644 index 0000000..2b6682e --- /dev/null +++ b/elementaryAlgo/areaOfTriangle.js @@ -0,0 +1,16 @@ +//Example 1: Area When Base and Height is Known +const areaBaseHeight = (base, height) => { + let area = (base * height) / 2; + return area; +}; +console.log(areaBaseHeight(2, 3)); +console.log(areaBaseHeight(3, 6)); +//Example 2: Area When All Sides are Known +//s = (a+b+c)/2 +//area = √(s(s-a)*(s-b)*(s-c)) +const areaAllSidesKnown = (side1, side2, side3) => { + let s = (side1 * side2 * side3) / 2; + let area = Math.sqrt(s * (s - side1) * (s - side2) * (s - side3)); + return area; +}; +console.log(areaAllSidesKnown(2, 3, 6)); diff --git a/elementaryAlgo/calculator.js b/elementaryAlgo/calculator.js new file mode 100644 index 0000000..c0748d5 --- /dev/null +++ b/elementaryAlgo/calculator.js @@ -0,0 +1,33 @@ +//simple calculation with if else statements +const calculatorWithIfElse = (operator, num1, num2) => { + let result; + if (operator === "+") { + result = num1 + num2; + } else if (operator === "-") { + result = num1 - num2; + } else if (operator === "*") { + result = num1 * num2; + } else { + result = num1 / num2; + } + return result; +}; +console.log(calculatorWithIfElse("*", 10, 10)); +const calculatorWithSwitch = (operator, num1, num2) => { + switch (operator) { + case "+": + result = num1 + num2; + break; + case "-": + result = num1 - num2; + break; + case "*": + result = num1 * num2; + break; + case "/": + result = num1 / num2; + break; + } + return result; +}; +console.log(calculatorWithSwitch("+", 10, 10)); diff --git a/elementaryAlgo/countCharacters.js b/elementaryAlgo/countCharacters.js new file mode 100644 index 0000000..f42eaab --- /dev/null +++ b/elementaryAlgo/countCharacters.js @@ -0,0 +1,11 @@ +const countCharacters = (str, letter) => { + let count = 0; + for (let i = 0; i < str.length; i++) { + //console.log(str[i]); + if (str.charAt(i) === letter) { + count++; + } + } + return count; +}; +console.log(countCharacters("hello world", "h")); diff --git a/elementaryAlgo/generateRandomString.js b/elementaryAlgo/generateRandomString.js new file mode 100644 index 0000000..0417df7 --- /dev/null +++ b/elementaryAlgo/generateRandomString.js @@ -0,0 +1,17 @@ +//Example 1: Generate Random Strings +const generateRandomString = (len) => { + let word = ""; + const characters = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + for (let i = 0; i < len; i++) { + word += characters.charAt(Math.floor(Math.random() * characters.length)); + } + return word; +}; +console.log(generateRandomString(7)); +//Example 2: Generate Random Strings Using Built-in Methods +const generateRandomStr = () => { + return Math.random().toString(36).substring(2, 7); +}; +console.log(generateRandomStr()); +console.log(String(36)); diff --git a/elementaryAlgo/highCommonFactor.js b/elementaryAlgo/highCommonFactor.js new file mode 100644 index 0000000..a8e1640 --- /dev/null +++ b/elementaryAlgo/highCommonFactor.js @@ -0,0 +1,24 @@ +//Example 1: Find HCF using for Loop +const highCommonFactor = (num1, num2) => { + let hcf; + for (let i = 1; i < num1 && i < num2; i++) { + if (num1 % i === 0 && num2 % i === 0) { + hcf = i; + } + } + return hcf; +}; +console.log(highCommonFactor(60, 20)); +//Example 2: HCF using while Loop and if...else +const highCommonFactorWhile = (num1, num2) => { + let result; + while (num1 !== num2) { + if (num1 > num2) { + result = num1 -= num2; + } else { + result = num2 -= num1; + } + } + return result; +}; +console.log(highCommonFactorWhile(1, 8)); diff --git a/elementaryAlgo/isLastDigitSame.js b/elementaryAlgo/isLastDigitSame.js new file mode 100644 index 0000000..53c6eba --- /dev/null +++ b/elementaryAlgo/isLastDigitSame.js @@ -0,0 +1,12 @@ +const isLastDigitSame = (num1, num2, num3) => { + const mod1 = num1 % 10; + const mod2 = num2 % 10; + const mod3 = num3 % 10; + if (mod1 === mod2 && mod2 === mod3) { + return true; + } + return false; +}; +console.log(isLastDigitSame(33, 33, 53)); +console.log(isLastDigitSame(33, 33, 53)); +console.log(isLastDigitSame(33, 32, 53)); diff --git a/elementaryAlgo/lowestCommonMultiple.js b/elementaryAlgo/lowestCommonMultiple.js new file mode 100644 index 0000000..1a3ee47 --- /dev/null +++ b/elementaryAlgo/lowestCommonMultiple.js @@ -0,0 +1,13 @@ +//Example 2: LCM Calculation Using HCF +const lowestCommonMultiple = (num1, num2) => { + let hcf; + for (let i = 1; i <= num1 && i <= num2; i++) { + if (num1 % i === 0 && num2 % i === 0) { + hcf = i; + } + } + let lcm = (num1 * num2) / 2; + return lcm; +}; +console.log(lowestCommonMultiple(30, 60)); +console.log(lowestCommonMultiple(6, 8)); diff --git a/elementaryAlgo/multiplicationTable.js b/elementaryAlgo/multiplicationTable.js new file mode 100644 index 0000000..6435663 --- /dev/null +++ b/elementaryAlgo/multiplicationTable.js @@ -0,0 +1,10 @@ +//Example 1: Multiplication Table Up to 10 +const multiplicationTable = (num) => { + let multiples = []; + for (let i = 1; i <= 10; i++) { + multiples.push(i * num); + } + return multiples; +}; +console.log(multiplicationTable(10)); +console.log(multiplicationTable(1)); diff --git a/elementaryAlgo/printHelloWorld.js b/elementaryAlgo/printHelloWorld.js new file mode 100644 index 0000000..0e9d395 --- /dev/null +++ b/elementaryAlgo/printHelloWorld.js @@ -0,0 +1,5 @@ +// A "Hello, World!" is a simple program that prints Hello, World! on the screen. +// Since it's a very simple program, this program is often used to introduce a +// new programming language to beginners. +const helloWorld = () => "hello world"; +console.log(helloWorld()); diff --git a/elementaryAlgo/raboAlgo/binarySearch.js b/elementaryAlgo/raboAlgo/binarySearch.js new file mode 100644 index 0000000..0566add --- /dev/null +++ b/elementaryAlgo/raboAlgo/binarySearch.js @@ -0,0 +1,36 @@ +const binarySearch = (array, num) => { + let start = 0; + let end = array.length - 1; + while (start < end) { + let mid = Math.floor((end + start) / 2); + let middleElem = array[mid]; + if (num === middleElem) return true; + else if (num < middleElem) { + end = mid; + } else { + start = mid + 1; + } + } + return false; +}; +console.log(binarySearch([2, 4, 6, 7, 9, 0], 10)); +console.log(binarySearch([2, 4, 6, 7, 9, 0], 2)); +console.log(binarySearch([2, 4, 6, 7, 9, 0], 7)); +function binarySearchTwo(array, num) { + let start = 0; + let end = array.length - 1; + do { + let mid = Math.floor((end + start) / 2); + let middleElem = array[mid]; + if (num === middleElem) return true; + else if (num < middleElem) { + end = mid; + } else { + start = mid + 1; + } + } while (start < end); + return false; +} +console.log(binarySearchTwo([2, 4, 6, 7, 9, 0], 10)); +console.log(binarySearchTwo([2, 4, 6, 7, 9, 0], 2)); +console.log(binarySearchTwo([2, 4, 6, 7, 9, 0], 7)); diff --git a/elementaryAlgo/raboAlgo/binaryTreeProblems.js b/elementaryAlgo/raboAlgo/binaryTreeProblems.js new file mode 100644 index 0000000..83d6309 --- /dev/null +++ b/elementaryAlgo/raboAlgo/binaryTreeProblems.js @@ -0,0 +1,182 @@ +class Node { + constructor(value) { + this.value = value; + this.right = null; + this.left = null; + } +} +const a = new Node("A"); +const b = new Node("B"); +const c = new Node("C"); +const d = new Node("D"); +const e = new Node("E"); +const f = new Node("F"); +a.right = b; +a.left = c; +b.right = d; +b.left = e; +c.right = f; +console.log(a); + +//printDepthFirst iterative +const printDepthFirst = (root) => { + if (root === null) return []; + let result = []; + let stack = [root]; + while (stack.length > 0) { + let element = stack.pop(); + result.push(element.value); + if (element.left) stack.push(element.left); + if (element.right) stack.push(element.right); + } + return result; +}; +console.log(printDepthFirst(a)); + +//printDepthRecursive +const printDepthFirstRecursive = (root) => { + if (root === null) return []; + const leftValue = printDepthFirstRecursive(root.left); + let rightValue = printDepthFirstRecursive(root.right); + return [root.value, ...rightValue, ...leftValue]; +}; +console.log(printDepthFirstRecursive(a)); + +//printBreadthFirst iterative +const printBreadthFirst = (root) => { + let result = []; + if (root === null) return []; + let queue = [root]; + while (queue.length > 0) { + let element = queue.shift(); + result.push(element.value); + if (element.right) queue.push(element.right); + if (element.left) queue.push(element.left); + } + return result; +}; +console.log(printBreadthFirst(a)); + +//tree Includes Recursive +const treeIncludesRecursive = (root, target) => { + if (root === null) return false; + if (root.value === target) return true; + let left = treeIncludesRecursive(root.left, target); + let right = treeIncludesRecursive(root.right, target); + return left === true || right === true ? true : false; +}; +console.log(treeIncludesRecursive(a, "A")); +//tree includes iterative +const treeIncludes = (root, target) => { + if (root === null) return false; + let stack = [root]; + while (stack.length > 0) { + let element = stack.pop(); + if (element.value === target) return true; + if (element.left) stack.push(element.left); + if (element.right) stack.push(element.right); + } + return false; +}; +console.log(treeIncludes(a, "A")); +console.log(treeIncludes(b, "B")); +console.log(treeIncludes(c, "C")); +console.log(treeIncludes("", "D")); +console.log(treeIncludes(null, "E")); +console.log(treeIncludes(a, "T")); + +const one = new Node(1); +const two = new Node(2); +const three = new Node(3); +const four = new Node(4); +const five = new Node(5); +const six = new Node(6); +one.right = two; +one.left = three; +two.right = four; +two.left = five; +three.right = six; +//tree sum recursively +const treeSumRecursive = (root) => { + if (root === null) return 0; + let rightSum = treeSumRecursive(root.right); + let leftSum = treeSumRecursive(root.left); + return root.value + rightSum + leftSum; +}; +console.log(treeSumRecursive(one)); +//tree sum iteratively using breadth-first +const treeSum = (root) => { + let sum = 0; + if (root === null) return 0; + let queue = [root]; + while (queue.length > 0) { + let element = queue.shift(); + sum += element.value; + if (element.left) stack.push(element.left); + if (element.right) stack.push(element.right); + } + return sum; +}; +console.log(treeSumRecursive(one)); + +//minimum value recursion +const treeMinValueRecursive = (root) => { + if (root === null) return Infinity; + let rootValue = root.value; + let leftValue = treeMinValueRecursive(root.left); + let rightValue = treeMinValueRecursive(root.right); + return Math.min(rootValue, leftValue, rightValue); +}; +console.log(treeMinValueRecursive(one)); + +//minimum value iterative +const treeMinValueIterative = (root) => { + let min = Infinity; + if (root === null) return Infinity; + let queue = [root]; + while (queue.length > 0) { + let element = queue.shift(); + min = Math.min(min, element.value); + if (element.right) queue.push(element.right); + if (element.left) queue.push(element.left); + } + return min; +}; +console.log(treeMinValueIterative(one)); + +//tree max value Iterative +const treeMaxValueIterative = (root) => { + let max = -Infinity; + if (root === null) return -Infinity; + + let queue = [root]; + while (queue.length > 0) { + let element = queue.shift(); + max = Math.max(max, element.value); + if (element.right) queue.push(element.right); + if (element.left) queue.push(element.left); + } + return max; +}; +console.log(treeMaxValueIterative(one)); +console.log(treeMaxValueIterative(null)); +//tree max value recursively +const treeMaxValueRecursive = (root) => { + let max = -Infinity; + if (root === null) return -Infinity; + let rootValue = root.value; + max = Math.max(max, rootValue); + let leftValue = treeMaxValueRecursive(root.left); + let rightValue = treeMaxValueRecursive(root.right); + return Math.max(max, rightValue, leftValue); +}; +console.log(treeMaxValueRecursive(one)); + +//max path tree problem +const maxPath = (root) => { + if (root === null) return -Infinity; + if (root.left === null && root.right === null) return root.value; + let maxLeftOrRight = Math.max(maxPath(root.left), maxPath(root.right)); + return root.value + maxLeftOrRight; +}; +console.log(maxPath(one)); diff --git a/elementaryAlgo/raboAlgo/bubbleSort.js b/elementaryAlgo/raboAlgo/bubbleSort.js new file mode 100644 index 0000000..8a5a2a4 --- /dev/null +++ b/elementaryAlgo/raboAlgo/bubbleSort.js @@ -0,0 +1,18 @@ +const bubbleSort = (arr) => { + //for every element compare with rest of elements + for (let i = 0; i < arr.length; i++) { + //start loop till one element less the end of array because of j + 1 maybe undefined + //element i from the left is consider to be sorted already, that is why -i + for (let j = 0; j < arr.length - 1 - i; j++) { + //if arr[j] > arr[j + 1] swap + if (arr[j] > arr[j + 1]) { + let temp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = temp; + } + } + } + return arr; +}; +console.log(bubbleSort([2, 1, 4, 2, 5, 16, 9])); +// O(n^2) diff --git a/elementaryAlgo/raboAlgo/cartesianProduct.js b/elementaryAlgo/raboAlgo/cartesianProduct.js new file mode 100644 index 0000000..2934781 --- /dev/null +++ b/elementaryAlgo/raboAlgo/cartesianProduct.js @@ -0,0 +1,11 @@ +const cartesianProduct = (arr1, arr2) => { + let cartesian = []; + for (let i = 0; i < arr1.length; i++) { + for (let j = 0; j < arr2.length; j++) { + cartesian.push([arr1[i], arr2[j]]); + } + } + return cartesian; +}; +console.log(cartesianProduct([1, 3], [4, 5, 6])); +// Time O(mn) and space diff --git a/elementaryAlgo/raboAlgo/climbingStaircase.js b/elementaryAlgo/raboAlgo/climbingStaircase.js new file mode 100644 index 0000000..e0cb086 --- /dev/null +++ b/elementaryAlgo/raboAlgo/climbingStaircase.js @@ -0,0 +1,15 @@ +//Given a staircase of n steps, count the number of distinct ways to climb to the top. +//you can either climb 1 step or 2 steps at a time +const climbingStaircase = (n) => { + //number of ways + let numOfWays = [1, 2]; + // start at i = 2; number of ways array have cover the initial positions of 0 and 1. + //remember you are looping through n + for (let i = 2; i <= n; i++) { + //number of ways array following fibbonuci series pattern + numOfWays[i] = numOfWays[i - 1] + numOfWays[i - 2]; + } + //note numOfWays[n -1] because array index start from zero + return numOfWays[n - 1]; +}; +console.log(climbingStaircase(5)); diff --git a/elementaryAlgo/raboAlgo/hasTable.js b/elementaryAlgo/raboAlgo/hasTable.js new file mode 100644 index 0000000..6e5f473 --- /dev/null +++ b/elementaryAlgo/raboAlgo/hasTable.js @@ -0,0 +1,70 @@ +class HashTable { + constructor(value) { + this.table = new Array(value); + this.size = value; + } + hash(key) { + let total = 0; + for (let i = 0; i < key.length; i++) { + total += key.charCodeAt(i); + } + total % this.size; + return total; + } + set(key, value) { + let index = this.hash(key); + let bucket = this.table[index]; + if (!bucket) { + this.table[index] = [[key, value]]; + } else { + let someItem = bucket.find((item) => item[0] === key); + if (someItem) { + bucket[1] = value; + } else { + bucket.push([key, value]); + } + } + } + get(key) { + let index = this.hash(key); + let bucket = this.table[index]; + if (bucket) { + let sameItem = bucket.find((item) => item[0] === key); + if (sameItem) { + return sameItem[1]; + } + } + return undefined; + } + remove(key) { + let index = this.hash(key); + let bucket = this.table[index]; + if (bucket) { + const sameKeyItem = bucket.find((item) => item[0] === key); + if (sameKeyItem) { + bucket.splice(bucket.indexOf(sameKeyItem), 1); + } + } + } + display() { + for (let i = 0; i < this.table.length; i++) { + if (this.table[i]) { + console.log(i, this.table[i]); + } + } + } +} +const map = new HashTable(50); +map.set("name", 30); +map.set("u", "animals"); +map.set("n", 300); +map.set("g", "ant"); +map.set("a", 378); +map.set("b", "bulk"); +console.log(map); +console.log(map.get("name")); +console.log(map.get("n")); +console.log(map.get("g")); +console.log(map.get("b")); +console.log(map.remove("a")); +map.display(); diff --git a/elementaryAlgo/raboAlgo/insertionSort.js b/elementaryAlgo/raboAlgo/insertionSort.js new file mode 100644 index 0000000..a380659 --- /dev/null +++ b/elementaryAlgo/raboAlgo/insertionSort.js @@ -0,0 +1,22 @@ +const insertionSort = (arr) => { + //start iteration at i = 1, because element at i = 0 with consider to be sorted + for (let i = 1; i < arr.length; i++) { + //element to the left of i = 1 should be j + let j = i - 1; + //element to be inserted + let elementInsert = arr[i]; + //all elements to the left of i must best compare and if element to the left of j is greater + // than element to be insert + while (j >= 0 && arr[j] > elementInsert) { + //insert at j + 1 the element at j + arr[j + 1] = arr[j]; + //conditions for the while loop check others element to the left of i + j--; + } + //after the while insert element at j + 1 to be element to be inserted + arr[j + 1] = elementInsert; + } + return arr; +}; +console.log(insertionSort([2, 1, 0, 3, 4, 9, 87, 6])); +//O(n^2) diff --git a/elementaryAlgo/raboAlgo/islandCountBFS.js b/elementaryAlgo/raboAlgo/islandCountBFS.js new file mode 100644 index 0000000..8de1b40 --- /dev/null +++ b/elementaryAlgo/raboAlgo/islandCountBFS.js @@ -0,0 +1,57 @@ +const directions = [ + [-1, 0], + [0, 1], + [1, 0], + [0, -1], +]; +//time O(m*n) and Space O(min(m, n)) because implemented BFS +//For the same solution for DFS with time O(m*n) and Space O(min(m, n)) +//I use BSF for better space performance +const numberOfIsland = (matrix) => { + if (matrix.length === 0) { + return 0; + } + let islandCount = 0; + let queue = []; + //sequential order + for (let row = 0; row < matrix.length; row++) { + for (let col = 0; col < matrix[0].length; col++) { + if (matrix[row][col] === 1) { + islandCount++; + queue.push([row, col]); + while (queue.length > 0) { + let current = queue.shift(); + const currRow = current[0]; + const currCol = current[1]; + matrix[currRow][currCol] = 0; + for (let i = 0; i < directions.length; i++) { + const [directionRow, directionCol] = directions[i]; + const currentRow = currRow + directionRow; + const currentCol = currCol + directionCol; + + if ( + currentRow < 0 || + currentRow >= matrix.length || + currentCol < 0 || + currentCol >= matrix[0].length + ) { + continue; + } + if (matrix[currentRow][currentCol] === 1) { + queue.push([currentRow, currentCol]); + } + } + } + } + } + } + return islandCount; +}; + +const matrix = [ + [1, 1, 1, 1, 0], + [1, 1, 0, 1, 0], + [1, 1, 0, 0, 1], + [0, 0, 0, 1, 1], +]; +console.log(numberOfIsland(matrix)); diff --git a/elementaryAlgo/raboAlgo/islandCountDFS.js b/elementaryAlgo/raboAlgo/islandCountDFS.js new file mode 100644 index 0000000..810493b --- /dev/null +++ b/elementaryAlgo/raboAlgo/islandCountDFS.js @@ -0,0 +1,52 @@ +const directions = [ + [-1, 0], + [0, 1], + [1, 0], + [0, -1], +]; +const numberOfIsland = (matrix) => { + if (matrix.length === 0) return 0; + let stack = []; + islandCount = 0; + //sequential check + for (let row = 0; row < matrix.length; row++) { + for (let col = 0; col < matrix[0].length; col++) { + if (matrix[row][col] === 1) { + islandCount++; + stack.push([row, col]); + while (stack.length > 0) { + let current = stack.pop(); + const [currRow, currCol] = current; + matrix[currRow][currCol] = 0; + for (let i = 0; i < directions.length; i++) { + //destructure movement up, down, right, left + const [x, y] = directions[i]; + // add the movement search to the current position + const currentRow = x + currRow; + const currentCol = y + currCol; + if ( + currentRow < 0 || + currentRow >= matrix.length || + currentCol < 0 || + currentCol >= matrix[0].length + ) { + continue; + } + if (matrix[currentRow][currentCol] === 1) { + stack.push([currentRow, currentCol]); + } + } + } + } + } + } + return islandCount; +}; + +const matrix = [ + [1, 1, 1, 1, 0], + [1, 1, 0, 1, 0], + [1, 1, 0, 0, 1], + [0, 0, 0, 1, 1], +]; +console.log(numberOfIsland(matrix)); diff --git a/elementaryAlgo/raboAlgo/linkListClass.js b/elementaryAlgo/raboAlgo/linkListClass.js new file mode 100644 index 0000000..1c3b723 --- /dev/null +++ b/elementaryAlgo/raboAlgo/linkListClass.js @@ -0,0 +1,308 @@ +//linkedList without tail +class Node { + constructor(value) { + this.value = value; + this.next = null; + } +} +class LinkedList { + constructor() { + this.head = null; + this.size = 0; + } + isEmpty() { + return this.size === 0; + } + getSize() { + return this.size; + } + //O(1) + prepend(value) { + let node = new Node(value); + if (this.isEmpty()) { + this.head = node; + } else { + node.next = this.head; + this.head = node; + } + + this.size++; + } + + //O(n) + append(value) { + let node = new Node(value); + if (this.isEmpty()) { + this.head = node; + } else { + let prev = this.head; + while (prev.next) { + prev = prev.next; + } + prev.next = node; + } + this.size++; + } + insert(value, index) { + if (index < 0 || index >= this.size) { + return "Invalid index"; + } + if (index === 0) { + this.prepend(value); + } + let node = new Node(value); + let prev = this.head; + let ind = 0; + while (prev) { + if (ind === index - 1) { + let next = prev.next; + prev.next = node; + node.next = next; + this.size++; + } + prev = prev.next; + ind++; + } + } + remove(index) { + if (index < 0 || index >= this.size) { + return "Invalid index"; + } + if (this.isEmpty()) { + return null; + } + if (index === 0) { + let head = this.head; + this.head = head.next; + this.size--; + return head.value; + } + let fast = this.head; + let ind = 0; + while (fast) { + if (ind === index - 1) { + let next = fast.next; + fast.next = fast.next.next; + this.size--; + return next.value; + } + fast = fast.next; + ind++; + } + } + removeValue(value) { + if (this.isEmpty()) { + return null; + } + if (value === this.head.value) { + let remove = this.head; + this.head = this.head.next; + this.size--; + return remove.value; + } + let prev = this.head; + + while (prev.next && prev.next.value !== value) { + prev = prev.next; + } + if (prev.next) { + let remove = prev.next; + prev.next = remove.next; + this.size--; + return remove.value; + } + return null; + } + search(value) { + if (this.isEmpty()) { + return -1; + } + let prev = this.head; + let ind = 0; + while (prev) { + if (prev.value === value) { + return ind; + } + ind++; + prev = prev.next; + } + return -1; + } + reverse() { + let prev = null, + cur = this.head; + while (cur) { + let next = cur.next; + cur.next = prev; + //advance prev pointer + prev = cur; + //advance curr pointer + cur = next; + } + //set head to be new item in the list + this.head = prev; + } + print() { + if (this.isEmpty()) { + console.log("list is empty"); + } else { + let result = ""; + let currentNode = this.head; + while (currentNode) { + result += `${currentNode.value} `; + currentNode = currentNode.next; + } + console.log(result); + return result; + } + } +} +let linkedList = new LinkedList(); +console.log(linkedList.isEmpty()); +console.log(linkedList.getSize()); +linkedList.prepend(2); +linkedList.prepend(40); +console.log(linkedList.print()); +linkedList.append(100); +console.log(linkedList.print()); +console.log(linkedList.insert(700, 1)); +console.log(linkedList.print()); +console.log(linkedList.remove(0)); +console.log(linkedList.print()); +console.log(linkedList.removeValue(700)); +console.log(linkedList.removeValue(1000)); +console.log(linkedList.print()); +console.log(linkedList.search(100)); +console.log(linkedList.reverse()); +console.log(linkedList.print()); +class NewNode { + constructor(value) { + this.value = value; + this.next = null; + } +} +//linkList with head +class LinkedListNew { + constructor() { + this.head = null; + this.tail = null; + this.size = 0; + } + isEmpty() { + return this.size === 0; + } + //prepend + prepend(value) { + let node = new NewNode(value); + if (this.isEmpty()) { + this.head = node; + this.tail = node; + } else { + let head = this.head; + this.head = node; + node.next = head; + } + this.size++; + return this.head; + } + append(value) { + let node = new NewNode(value); + if (this.isEmpty()) { + this.head = node; + this.tail = node; + } else { + let tail = this.tail; + this.tail = node; + tail.next = node; + } + this.size++; + return this.head; + } + insert(value, index) { + if (index < 0 || index >= this.size) return "Invalid index"; + if (index === 0) { + this.prepend(value); + } + if (index === this.size - 1) { + this.append(value); + } + let newNode = new NewNode(value); + let current = this.head; + let ind = 0; + while (current.next) { + if (ind === index - 1) { + let node = current.next; + current.next = newNode; + newNode.next = node; + this.size++; + } + index++; + current = current.next; + } + return this.head; + } + remove(index) { + if (index < 0 || index >= this.size - 1) return "Invilid index"; + if (index === 0) { + let head = this.head; + this.head = head.next; + this.size--; + return head; + } + let current = this.head; + let ind = 0; + while (current) { + if (ind === index - 1) { + let next = current.next; + current.next = next.next; + this.size--; + return next; + } + ind++; + current = current.next; + } + } + removeFromEnd() { + if (this.isEmpty()) { + return null; + } + let head = this.tail.value; + if (this.size === 1) { + this.head = null; + this.tail = null; + this.size--; + return head.value; + } else { + let prev = this.head; + while (prev.next !== this.tail) { + prev = prev.next; + } + prev.next = null; + this.tail = prev; + } + this.size--; + return head; + } + print() { + let current = this.head; + let result = ""; + while (current) { + result += `${current.value} `; + current = current.next; + } + return result; + } +} +let newLinkedList = new LinkedListNew(); +newLinkedList.prepend(2); +newLinkedList.prepend(400); +console.log(newLinkedList); +console.log(newLinkedList.isEmpty()); +console.log(newLinkedList.print()); +console.log(newLinkedList.append(90)); +console.log(newLinkedList.print()); +console.log(newLinkedList.insert(600, 1)); +console.log(newLinkedList.insert(700, 3)); +console.log(newLinkedList.removeFromEnd(4)); +console.log(newLinkedList); +console.log(newLinkedList.print()); diff --git a/elementaryAlgo/raboAlgo/linkedListProblems.js b/elementaryAlgo/raboAlgo/linkedListProblems.js new file mode 100644 index 0000000..b4a86c9 --- /dev/null +++ b/elementaryAlgo/raboAlgo/linkedListProblems.js @@ -0,0 +1,193 @@ +class Node { + constructor(value) { + this.value = value; + this.next = null; + } +} +const a = new Node("A"); +const b = new Node("B"); +const c = new Node("C"); +const d = new Node("D"); +a.next = b; +b.next = c; +c.next = d; + +//print to console iteratively +const printLinkedList = (head) => { + let current = head; + while (current) { + console.log(current.value); + current = current.next; + } +}; +//print to console recursively +console.log(printLinkedList(a)); +const printLinkedListRecursive = (head) => { + if (head === null) return; + console.log(head.value); + printLinkedListRecursive(head.next); +}; +console.log(printLinkedListRecursive(a)); + +//linked list values iteratively +const linkedListValue = (head) => { + let values = []; + let current = head; + while (current !== null) { + values.push(current.value); + current = current.next; + } + return values; +}; +console.log(linkedListValue(a)); + +//linked list values recursively +const linkedListRecursive = (head) => { + let results = []; + results.push(head.value); + fillCallList(head.next, results); + return results; +}; +function fillCallList(head, results) { + if (head === null) return; + results.push(head.value); + fillCallList(head.next, results); +} +console.log(linkedListRecursive(a)); +const one = new Node(1); +const two = new Node(2); +const three = new Node(3); +const four = new Node(4); + +one.next = two; +two.next = three; +three.next = four; + +//sumList +const sumList = (head) => { + let total = 0; + let current = head; + while (current) { + total += current.value; + current = current.next; + } + return total; +}; +console.log(sumList(one)); + +//sumList +const sumListRecursive = (head) => { + if (head === null) return 0; + return head.value + sumListRecursive(head.next); +}; + +console.log(sumListRecursive(one)); + +// target node +const targetNode = (head, val) => { + let current = head; + while (current) { + if (current.value === val) { + return true; + } + current = current.next; + } + return false; +}; +console.log(targetNode(a, "D")); +console.log(targetNode(a, "B")); +console.log(targetNode(a, "")); + +//target node recursively +const targetNodeRecursive = (head, val) => { + if (head === null) return false; + if (head.value === val) return true; + return targetNodeRecursive(head.next, val); +}; +console.log(targetNodeRecursive(a, "B")); +console.log(targetNodeRecursive(a, "B")); +console.log(targetNodeRecursive(a, "")); + +const getValue = (head, index) => { + let current = head; + let ind = 0; + while (current) { + if (ind === index) { + return current.value; + } + + ind++; + current = current.next; + } + return null; +}; +console.log(getValue(a, 1)); +console.log(getValue(a, 2)); +console.log(getValue(a, 3)); +console.log(getValue(a, 4)); + +const getValueRecursive = (head, index) => { + if (head === null) return null; + if (index === 0) return head.value; + return getValueRecursive(head.next, index - 1); +}; +console.log(getValueRecursive(a, 1)); +console.log(getValueRecursive(a, 2)); +console.log(getValueRecursive(a, 3)); +console.log(getValueRecursive(a, 4)); + +const reverseList = (head) => { + let current = head; + let prev = null; + while (current) { + let next = current.next; + current.next = prev; + + prev = current; + current = next; + } + return prev; +}; + +console.log(reverseList(a)); + +const zippList = (head1, head2) => { + let tail = head1; + let current1 = head1.next; + let current2 = head2; + let count = 0; + while (current1 !== null && current2 !== null) { + //when count is even add current2 to tail + if (count % 2 === 0) { + tail.next = current2; + //shift current2 current node to the next + current2 = current2.next; + } else { + //else add current1 to tail + tail.next = current1; + //shift current1 current node to the next + current1 = current1.next; + } + //shift tail to the next iteration + tail = tail.next; + count++; + } + //if the while loop finishes and there is still + //element in either list then append them to the tail + if (current1 !== null) { + tail.next = current1; + } + if (current2 !== null) { + tail.next = current2; + } + //return the entry head + return head1; +}; +const five = new Node(5); +const six = new Node(6); +const seven = new Node(7); +five.next = six; +six.next = seven; +console.log(one); +console.log(five); +console.log(zippList(one, five)); diff --git a/elementaryAlgo/raboAlgo/mergeSort.js b/elementaryAlgo/raboAlgo/mergeSort.js new file mode 100644 index 0000000..fd9b93f --- /dev/null +++ b/elementaryAlgo/raboAlgo/mergeSort.js @@ -0,0 +1,32 @@ +const mergeSort = (arr) => { + //whenever the elements are less than two return the array + if (arr.length < 2) return arr; + // get mid point + let mid = Math.floor(arr.length / 2); + // copy the element from start but not including the middle + let left = arr.slice(0, mid); + // copy the element from the middle to the end + let right = arr.slice(mid); + //make a recursive call for both left and right until + //all elements are one. Call the merge helper function + //pass in left and right. + return merge(mergeSort(left), mergeSort(right)); +}; +const merge = (leftArr, rightArr) => { + let sorted = []; + //check if both leftArr and rightArr still have elements + while (leftArr.length && rightArr.length) { + //check if the first element of left array is less than + // first element of right array, then remove it and push + //to the sorted array + if (leftArr[0] <= rightArr[0]) { + sorted.push(leftArr.shift()); + } else { + //else + sorted.push(rightArr.shift()); + } + } + //copy in this order for the elements to sorted and return + return [...sorted, ...leftArr, ...rightArr]; +}; +console.log(mergeSort([9, 2, -1, -6, 8, 3])); diff --git a/elementaryAlgo/raboAlgo/numOfminutes.js b/elementaryAlgo/raboAlgo/numOfminutes.js new file mode 100644 index 0000000..db3f898 --- /dev/null +++ b/elementaryAlgo/raboAlgo/numOfminutes.js @@ -0,0 +1,38 @@ +// A company has n employees with a unique ID for each employee from 0 to n - 1. The head of the company +// is the one with headID. Each employee has one direct manager given in the manager array where +// manager[i] is the direct manager of the i-th employee, manager[headID] = -1. Also, it is +// guaranteed that the subordination relationships have a tree structure. The head of the company wants to +// inform all the company employees of an urgent piece of news. He will inform his direct subordinates, and +// they will inform their subordinates, and so on until all employees know about the urgent news. The i-th employee +// needs informTime[i] minutes to inform all of his direct subordinates (i.e., After informTime[i] minutes, all +// his direct subordinates can start spreading the news). Return the number of minutes needed to inform all the +// employees about the urgent news. +// Example 1: + +// Input: n = 1, headID = 0, manager = [-1], informTime = [0] +// Output: 0 +// Explanation: The head of the company is the only employee in the company. +// Example 2: + +// Input: n = 6, headID = 2, manager = [2,2,-1,2,2,2], informTime = [0,0,1,0,0,0] +// Output: 1 +// Explanation: The head of the company with id = 2 is the direct manager of all the employees in the company and needs 1 minute to inform them all. +// The tree structure of the employees in the company is shown. + +const numOfMinutes = (n, headID, manager, informTime) => { + const tree = [...Array(n)].map(() => []); + for (let i = 0; i < n; i++) { + if (manager[i] !== -1) tree[manager[i]].push(i); + } + return traverse(headID, tree, informTime); +}; + +const traverse = (node, tree, informTime) => { + let maxTime = 0; + + for (let subordinate of tree[node]) { + maxTime = Math.max(maxTime, traverse(subordinate, tree, informTime)); + } + return maxTime + informTime[node]; +}; +console.log(numOfMinutes(6, 2, [2, 2, -1, 2, 2, 2], [0, 0, 1, 0, 0, 0])); diff --git a/elementaryAlgo/raboAlgo/numberOfIsland.js b/elementaryAlgo/raboAlgo/numberOfIsland.js new file mode 100644 index 0000000..ba295ba --- /dev/null +++ b/elementaryAlgo/raboAlgo/numberOfIsland.js @@ -0,0 +1,30 @@ +const numIslands = (grid) => { + let count = 0; + for (let r = 0; r < grid.length; r += 1) { + for (let c = 0; c < grid[r].length; c += 1) { + if (grid[r][c] === "1") { + count = count + explore(grid, r, c); + } + } + } + return count; +}; + +let explore = (grid, r, c) => { + if ( + r < 0 || + r > grid.length - 1 || + c < 0 || + c > grid[r].length - 1 || + grid[r][c] === "0" + ) { + return; + } + grid[r][c] = "0"; + explore(grid, r + 1, c); + explore(grid, r - 1, c); + explore(grid, r, c + 1); + explore(grid, r, c - 1); + return 1; +}; +//BRD-hH7G-Mzu3-LNDv1 \ No newline at end of file diff --git a/elementaryAlgo/raboAlgo/orangesRotting.js b/elementaryAlgo/raboAlgo/orangesRotting.js new file mode 100644 index 0000000..a6c47cd --- /dev/null +++ b/elementaryAlgo/raboAlgo/orangesRotting.js @@ -0,0 +1,75 @@ +/** + * @param {number[][]} grid + * @return {number} + */ +var orangesRotting = function (grid) { + //Initialize queue for our BFS, Number of fresh oranges, and time to be returned. + let queue = [], + time = 0, + oranges = 0; + + //Traverse matrix. If we find a fresh orange, increment orange count. + //If we find a rotten one, add it to the queue. + for (let row = 0; row < grid.length; row++) { + for (let col = 0; col < grid[0].length; col++) { + if (grid[row][col] === 1) oranges++; + else if (grid[row][col] === 2) queue.push([row, col, 0]); + } + } + //Dirs will help us check neighbors during our BFS. Adding these coordinates + //to a point just gets right, left, up and down. endR and endC are used later + //to make sure neighbor coords are within grid. + let dir = [ + [-1, 0], + [0, 1], + [1, 0], + [0, -1], + ]; + //Loop while queue is not empty and there are still fresh oranges. + while (queue.length && oranges) { + //Entry within queue can be destructured to make it easier to work with. + //Each queue entry has a row, column and number of minutes taken for + //infection to reach. + const [rRow, cCol, mins] = queue.shift(); + + //If orange is still fresh, we mark it as rotten, decrement our fresh oranges + //count and set time to = mins. Since we BFSing, the time it takes to infect + //the last orange will be the time to infect all. Once all oranges have + //been infected, our orange count will = 0 and our condition in while loop + //will stop the loop. Time can then be returned + if (grid[rRow][cCol] === 1) { + grid[rRow][cCol] = 2; + oranges--; + time = mins; + } + + //Here's where our dir array above comes in handy. We destructure + //each entry and add it to our current to get neighbor coords below. + for (let [r, c] of dir) { + let nextRow = r + rRow, + nextCol = c + cCol; + //Here we obtain our new or neighbor coordinates by adding currentRow + //and addRow of dir. Same for col. + + //Here we check to make sure new coordinates lie within the grid. + if ( + nextRow < 0 || + nextCol < 0 || + nextRow >= grid.length || + nextCol >= grid[0].length + ) + continue; + //If neighbor coord is valid, and there is a fresh orange at those coordinates + //we push coordinates to our BFS to be infected next. We also increment the + //mins count to track time taken to spread to that orange. + if (grid[nextRow][nextCol] === 1) { + queue.push([nextRow, nextCol, mins + 1]); + } + } + } + + //If we still have uninfected oranges, we return -1 because it won't spread + //to all. Otherwise, we simply return the time from initial infected to last + //infected orange. + return oranges ? -1 : time; +}; diff --git a/elementaryAlgo/raboAlgo/quickSort.js b/elementaryAlgo/raboAlgo/quickSort.js new file mode 100644 index 0000000..e9e165f --- /dev/null +++ b/elementaryAlgo/raboAlgo/quickSort.js @@ -0,0 +1,20 @@ +const quickSort = (arr) => { + //this condition is can arr.length === 1 || arr.length === 0 because arr.length can be zero + if (arr.length < 2) return arr; + //pick last element as pivot + let pivot = arr[arr.length - 1], + left = [], + right = []; + //iterate from first element but not include the pivot + for (let i = 0; i < arr.length - 1; i++) { + //current element is greater than pivot + if (arr[i] > pivot) right.push(arr[i]); + //else + else left.push(arr[i]); + } + //call quick sort recusively until it reaches base case + //and the base could be empty array or array with single element, + //copy the base cases into a new array with the pivot in the centre + return [...quickSort(left), pivot, ...quickSort(right)]; +}; +console.log(quickSort([9, 4, 5, 6, 7, 8, 10, 11])); diff --git a/elementaryAlgo/raboAlgo/twoCrystalBalls.js b/elementaryAlgo/raboAlgo/twoCrystalBalls.js new file mode 100644 index 0000000..bf8bdb0 --- /dev/null +++ b/elementaryAlgo/raboAlgo/twoCrystalBalls.js @@ -0,0 +1,20 @@ +//Given to crystal balls that will break if dropped from high enough distance, +//determine the exact spot in which it will break in most optimized way. +const twoCrystalBall = (breaks) => { + const jmpAmount = Math.floor(Math.sqrt(breaks.length)); + let i = jmpAmount; + for (; i < breaks.length; i++) { + if (breaks[i]) { + break; + } + } + i--; + for (let j = 0; j < jmpAmount && i < breaks.length; ++j, ++i) { + if (breaks[i]) { + return i; + } + } + return -1; +}; +console.log(twoCrystalBall(["f", "f", "f", "t", "f", "f", "f", "f", "t"])); +console.log(twoCrystalBall(["f", "f", "f", "t", "f"])); diff --git a/elementaryAlgo/raboAlgo/twoDArrayOrMatrixBFS.js b/elementaryAlgo/raboAlgo/twoDArrayOrMatrixBFS.js new file mode 100644 index 0000000..d2851cf --- /dev/null +++ b/elementaryAlgo/raboAlgo/twoDArrayOrMatrixBFS.js @@ -0,0 +1,39 @@ +const directions = [ + [-1, 0], + [0, 1], + [1, 0], + [0, -1], +]; +// time O(n) and space O(n) +const bfs = (matrix) => { + let seen = new Array(matrix.length) + .fill(0) + .map(() => new Array(matrix[0].length).fill(false)); + let values = []; + let queue = [[0, 0]]; + while (queue.length > 0) { + let [row, col] = queue.shift(); + if ( + row < 0 || + row >= matrix.length || + col < 0 || + col >= matrix[0].length || + seen[row][col] + ) + continue; + values.push(matrix[row][col]); + seen[row][col] = true; + for (let i = 0; i < directions.length; i++) { + let [x, y] = directions[i]; + queue.push([row + x, col + y]); + } + } + return values; +}; +const matrix = [ + [1, 2, 3, 4, 5], + [6, 7, 8, 9, 10], + [11, 12, 13, 14, 15], + [16, 17, 18, 19, 20], +]; +console.log(bfs(matrix)); diff --git a/elementaryAlgo/raboAlgo/twoDArrayOrMatrixDFS.js b/elementaryAlgo/raboAlgo/twoDArrayOrMatrixDFS.js new file mode 100644 index 0000000..ffdfe26 --- /dev/null +++ b/elementaryAlgo/raboAlgo/twoDArrayOrMatrixDFS.js @@ -0,0 +1,82 @@ +//recursive solution for BFS matrix +let directions = [ + [-1, 0], + [0, 1], + [1, 0], + [-1, 0], +]; +//time O(n) and space O(n) +const traversalDfS = (matrix) => { + const seen = new Array(array.length) + .fill(0) + //because the inner array are of the same length we can arrray[0] + .map(() => new Array(matrix[0].length).fill(false)); + let values = []; + console.log(seen); + dfs(matrix, 0, 0, seen, values); + return values; +}; + +const dfs = (matrix, row, col, seen, values) => { + if ( + row < 0 || + col < 0 || + row >= matrix.length || + col >= matrix[row].length || + seen[row][col] + ) + return; + values.push(matrix[row][col]); + seen[row][col] = true; + for (let i = 0; i < directions.length; i++) { + const directionDir = directions[i]; + dfs(matrix, row + directionDir[0], col + directionDir[1], seen, values); + } + // dfs(matrix, row - 1, col, seen, values); + // dfs(matrix, row, col + 1, seen, values); + // dfs(matrix, row + 1, col, seen, values); + // dfs(matrix, row, col - 1, seen, values); +}; +let array = [ + [1, 2, 3, 4, 5], + [6, 7, 8, 9, 10], + [11, 12, 13, 14, 15], + [16, 17, 18, 19, 20], +]; +console.log(traversalDfS(array)); +//[ 1, 2, 3, 4, 5, 10, 15, 20, 19, 14, 9, 8, 13, 18, 17, 12, 7, 6, 11, 16 ] + +//iterative solution +const bfsIterative = (matrix) => { + let seen = new Array(matrix.length) + .fill(0) + .map(() => new Array(matrix[0].length).fill(false)); + console.log(seen); + let values = []; + let stack = [[0, 0]]; + while (stack.length > 0) { + let [row, col] = stack.pop(); + if ( + row < 0 || + row >= matrix.length || + col < 0 || + col >= matrix[0].length || + seen[row][col] + ) + continue; + seen[row][col] = true; + values.push(matrix[row][col]); + for (let i = 0; i < directions.length; i++) { + const [x, y] = directions[i]; + stack.push([row + x, col + y]); + } + } + return values; +}; +let arr = [ + [1, 2, 3, 4, 5], + [6, 7, 8, 9, 10], + [11, 12, 13, 14, 15], + [16, 17, 18, 19, 20], +]; +console.log(bfsIterative(arr)); diff --git a/elementaryAlgo/raboAlgo/twoDBasic.js b/elementaryAlgo/raboAlgo/twoDBasic.js new file mode 100644 index 0000000..a2299cd --- /dev/null +++ b/elementaryAlgo/raboAlgo/twoDBasic.js @@ -0,0 +1,14 @@ +const twoDBasic = (arr) => { + for (let i = 0; i < arr.length; i++) { + for (let j = 0; j < arr[0].length; j++) { + console.log(arr[i][j]); + } + } +}; +console.log( + twoDBasic([ + [1, 2, 3], + [4, 5, 6], + [7, 8, 9], + ]) +); diff --git a/elementaryAlgo/raboAlgo/wallsandGates.js b/elementaryAlgo/raboAlgo/wallsandGates.js new file mode 100644 index 0000000..cca4f73 --- /dev/null +++ b/elementaryAlgo/raboAlgo/wallsandGates.js @@ -0,0 +1,58 @@ +// You are given a m x n 2D grid initialized with these three possible values. + +// -1 - A wall or an obstacle. 0 - A gate. INF - Infinity means an empty room. +// We use the value 231 - 1 = 2147483647 to represent INF as you may assume that +// the distance to a gate is less than 2147483647. Fill each empty room with the +// distance to its nearest gate. If it is impossible to reach a gate, it should be +// filled with INF. + +let directions = [ + [-1, 0], + [1, 0], + [0, -1], + [0, 1], +]; + +const wallsAndGates = (rooms) => { + if (!rooms || rooms.length === 0) { + return; + } + + let rows = rooms.length; + let cols = rooms[0].length; + + for (let i = 0; i < rows; i++) { + for (let j = 0; j < cols; j++) { + // find all gates + if (rooms[i][j] === 0) { + traverse(rooms, i, j, rows, cols, 0); + } + } + } + return rooms; +}; + +function traverse(rooms, i, j, rows, cols, dist) { + //we have to set boundary in which we want to perform our depth first search + if (i >= 0 && i < rows && j >= 0 && j < cols) { + //even we within this bounded, if the element is not -1 and element is greater than or equal to the distance + if (rooms[i][j] !== -1 && rooms[i][j] >= dist) { + // set the element to be the new distance + rooms[i][j] = dist; + //perform depth first and increase the distance + traverse(rooms, i + 1, j, rows, cols, dist + 1); + traverse(rooms, i, j + 1, rows, cols, dist + 1); + traverse(rooms, i - 1, j, rows, cols, dist + 1); + traverse(rooms, i, j - 1, rows, cols, dist + 1); + } + } +} +let INF = 2187983647; +console.log( + wallsAndGates([ + [INF, -1, 0, INF], + [INF, INF, INF, -1], + [INF, -1, INF, -1], + [0, -1, INF, INF], + ]) +); diff --git a/elementaryAlgo/randomIntegers.js b/elementaryAlgo/randomIntegers.js new file mode 100644 index 0000000..4535b64 --- /dev/null +++ b/elementaryAlgo/randomIntegers.js @@ -0,0 +1,10 @@ +//Example 3: Integer Value between 1 and 10 +const randomIntegers = (min, max) => { + return Math.floor(Math.random() * (max - min) + min); +}; +console.log(randomIntegers(1, 10)); +console.log(randomIntegers(1, 10)); +//Example 4: Integer Value between Two Numbers (Inclusive) +const randomNumbers = (min, max) => { + return Math.floor(Math.random() * (max - min + 1) + min); +}; diff --git a/elementaryAlgo/replaceAllOcurrenceStr.js b/elementaryAlgo/replaceAllOcurrenceStr.js new file mode 100644 index 0000000..2c6e222 --- /dev/null +++ b/elementaryAlgo/replaceAllOcurrenceStr.js @@ -0,0 +1,10 @@ +const replaceAllOcurrenceStr = (str, word, rep) => { + return str.split(word).join(rep); +}; +console.log( + replaceAllOcurrenceStr( + "hello world, I love you all. I mean you are my all in all", + "all", + "ah" + ) +); diff --git a/elementaryAlgo/setOperations.js b/elementaryAlgo/setOperations.js new file mode 100644 index 0000000..ff7ed4e --- /dev/null +++ b/elementaryAlgo/setOperations.js @@ -0,0 +1,42 @@ +//intersection of a sets +const intersectionOfSet = (setA, setB) => { + let intersection = new Set(); + for (let i of setA) { + if (setB.has(i)) { + intersection.add(i); + } + } + return intersection; +}; +console.log( + intersectionOfSet(new Set([1, 2, 5, 7, 8]), new Set([2, 4, 6, 8, 9])) +); +//union of sets +const unionOfSet = (setA, setB) => { + let union = new Set(setA); + for (let i of setB) { + union.add(i); + } + return union; +}; +console.log(unionOfSet(new Set([1, 2, 5, 7, 8]), new Set([2, 4, 6, 8, 9]))); +//difference of setA and setB +const differenceOfSet = (setA, setB) => { + for(let i of setB){ + if(setA.has(i)){ + setA.delete(i) + } + } + return setA +} +console.log(differenceOfSet(new Set([1, 2, 5, 7, 8]), new Set([2, 4, 6, 8, 9]))); +//subse of setA and setB +const subSet = (setA, setB) => { + for(let i of setB){ + if(!setA.has(i)){ + return false + } + } + return true +} +console.log(subSet(new Set([1, 2, 5, 7, 8]), new Set([2, 4, 6, 8, 9]))) \ No newline at end of file diff --git a/elementaryAlgo/splitArrayIntoChunks.js b/elementaryAlgo/splitArrayIntoChunks.js new file mode 100644 index 0000000..3d913d4 --- /dev/null +++ b/elementaryAlgo/splitArrayIntoChunks.js @@ -0,0 +1,18 @@ +const splitArrayIntoChunks = (array, chunk) => { + let result = []; + for (let i = 0; i < array.length; i += chunk) { + let temp = array.slice(i, i + chunk); + result.push(temp); + } + return result; +}; +console.log(splitArrayIntoChunks([7, 8, 8, 9, 10, 11, 12, 13, 14, 15], 3)); +const splitArrayIntoChunk = (array, chunk) => { + let result = []; + while (array.length > 0) { + let temp = array.splice(0, chunk); + result.push(temp); + } + return result; +}; +console.log(splitArrayIntoChunk([7, 8, 8, 9, 10, 11, 12, 13, 14, 15], 2)); diff --git a/elementaryAlgo/squareRoot.js b/elementaryAlgo/squareRoot.js new file mode 100644 index 0000000..330f629 --- /dev/null +++ b/elementaryAlgo/squareRoot.js @@ -0,0 +1,5 @@ +const squareRoot = (number) => { + return Math.sqrt(number); +}; +console.log(squareRoot(64)); +console.log(squareRoot(34)); diff --git a/elementaryAlgo/strInAnotherStr.js b/elementaryAlgo/strInAnotherStr.js new file mode 100644 index 0000000..c786bcf --- /dev/null +++ b/elementaryAlgo/strInAnotherStr.js @@ -0,0 +1,8 @@ +const stringInAnotherStr = (string, str) => { + if (string.indexOf(str) !== -1) { + return str; + } + return ""; +}; +console.log(stringInAnotherStr("hello world I love you so much", "lo")); +console.log(stringInAnotherStr("hello world I love you so much", "hi")); diff --git a/elementaryAlgo/sum.js b/elementaryAlgo/sum.js new file mode 100644 index 0000000..61d2590 --- /dev/null +++ b/elementaryAlgo/sum.js @@ -0,0 +1,20 @@ +//Example 1: Sum of Natural Numbers Using for Loop +const sumForLoop = (num) => { + let sum = 0; + for (let i = 1; i <= num; i++) { + sum += i; + } + return sum; +}; +console.log(sumForLoop(10)); +//Example 2: Sum of Natural Numbers Using while Loop +const sumWhileLoop = (num) => { + let sum = 0, + i = 1; + while (i <= num) { + sum += i; + i++; + } + return sum; +}; +console.log(sumWhileLoop(10)); diff --git a/elementaryAlgo/swapTwoVariable.js b/elementaryAlgo/swapTwoVariable.js new file mode 100644 index 0000000..db8017c --- /dev/null +++ b/elementaryAlgo/swapTwoVariable.js @@ -0,0 +1,35 @@ +//Example 1: Using a Temporary Variable +const swapTemporaryVariable = (arr) => { + let [a, b] = arr; + let temp = a; + a = b; + b = temp; + return [a, b]; +}; +console.log(swapTemporaryVariable([20, 40])); + +//Example 2: Using es6(ES2015) Destructuring assignment +const swapEs6 = (arr) => { + let [a, b] = arr; + [b, a] = [a, b]; + return [a, b]; +}; +console.log(swapEs6([20, 40])); +//Example 3: Using Arithmetic Operators +const swapArithmetic = (arr) => { + let [a, b] = arr; + a = a + b; + b = a - b; + a = a - b; + return [a, b]; +}; +console.log(swapArithmetic([20, 40])); +//Example 4: Using Bitwise XOR operator +const swapBitwiseXOR = (arr) => { + let [a, b] = arr; + a = a ^ b; + b = a ^ b; + a = a ^ b; + return [a, b]; +}; +console.log(swapBitwiseXOR([20, 40]));