I have been able to successfully address several JavaScript problems, and am making an effort to continue improving my skills in problem solving.
JavaScript
javascript-problem-solving
Unit converter
//meter to kilometerletkilo;functionmeterToKilo(meter){kilo=meter/1000;letkiloIntpart=Math.floor(kilo);letkiloDeciPart=((kilo%1).toFixed(3)).replace('0.','');letkiloResult=kiloIntpart+' kilo '+kiloDeciPart+' meter';returnkiloResult;}letkilometer=meterToKilo(650);console.log(kilometer)
Leap Year
functionisLeapYear(year){if(year%4==0&&year%100!=0){returntrue;}elseif(year%400==0){returntrue;}else{returnfalse;}}constcheckLeapYear=isLeapYear(1700);console.log(checkLeapYear);//solution number 2functionleapYear(year){if((year%4==0&&year%100!=0)||year%400==0){returntrue;}else{returnfalse;}}console.log(leapYear(2000))//solution number 3functioncheckingLeapYear(year){if(year%4==0){if(year%100!=0){returntrue;}elseif(year%400==0){returntrue;}else{returnfalse;}}else{returnfalse;}}console.log(checkingLeapYear(2200))
Factorial using for loop
//factorial // 3! = 1X2X3// 4! = 1X2X3X4// 5! = 1X2X3X4X5// factorial using for loopfunctionfactorial(n){letfact=1;for(leti=1;i<=n;i++){fact=fact*i;}returnfact;}//start from the current numberfunctionfactorialBack(n){letfact=1;for(leti=n;i>=1;i--){fact=fact*i;}returnfact}//console.log(factorialBack(4))//console.log(factorial(10))
Factorial using while loop
//factorial // 3! = 1X2X3// 4! = 1X2X3X4// 5! = 1X2X3X4X5//factorial using while loopfunctionfactorial1(n){leti,fact;i=1;fact=1;while(i<=n){fact=fact*i;i++;}returnfact;}console.log(factorial1(5))
Factorial in Recursive way
//factorial // 3! = 1X2X3// 4! = 1X2X3X4// 5! = 1X2X3X4X5//factorial using recursive function// 0! = 1// 2! = 1X2// 3! = 1X2X3 == 2! X 3// 4! = 1X2X3X4 == 3! X4// 5! = 1X2X3X4X5 == 4! X 5// 6! = (6-1)! X 6// 7! = (7-1)! X 7// n! = (n-1)! X nfunctionrecurFactorial(n){letfact;if(n==0){return1;}else{returnn*recurFactorial(n-1);}}console.log(recurFactorial(5));
//fibonacci series using while loopfunctionfibonacci1(n){leti,fibo;fibo=[0,1];i=2;while(i<=n){fibo[i]=fibo[i-1]+fibo[i-2];i++;}returnfibo;}console.log(fibonacci1(10));
fibonacci sequence recursive way
//create a fibiancci series in a recursive way//fibo[n] = fibo[n-1] + fibo[n-2]//[0, 1, 1, 2, 3, 5, 8, 13, 21..]functionfibonacci3(n){if(n==0){return[0];}if(n==1){return[0,1];}else{//calculate array nth elementletfibo=fibonacci3(n-1);letnextElement=fibo[n-1]+fibo[n-2];fibo.push(nextElement);returnfibo;}}varresult1=fibonacci3(10);console.log(result1);
nth number of fibonacci series
//get nth number fibonacci series using recursive function//fibo[n] = fibo[n-1] + fibo[n-2]functionfib(n){if(n==0){return0;}if(n==1){return1;}returnfib(n-1)+fib(n-2);}letresult=fib(100);console.log(result);
Prime number
//simple and not that much efficientwayfunctionisPrime(n){if(n==1){returnfalse;}elseif(n==2){returntrue;}else{for(leti=2;i<n;i++){if(n%i==0){returnfalse;}}returntrue;}}letresult=isPrime(3);console.log(result);//mediam efficient wayfunctionisPrime1(n){if(n===1){returnfalse;}elseif(n===2||n===3){returntrue;}else{for(i=2;i<=Math.floor(Math.sqrt(n));i++){if(n%i==0){returnfalse;}}returntrue;}}letresult1=isPrime1(13);// console.log(result1);
Swap value
// 4 way to swap variable values in JavaScript// suppose we have two variable a and b, we want to swap there values// for example the value of a and b are 2, 3// the result would be a = 3, b = 2leta=2;letb=3;// using temp variablelettemp=a;a=b;b=temp;console.log(a,b)// a = 3, b = 2// using array destructuring [a,b]=[b,a];console.log(a,b)// a = 3, b = 2// using math in one lineb=a+(a=b)-b;console.log(a,b)// a = 3, b = 2// using arithmetic operatora=a+b;// add a, b then assign to a(a = 5)b=a-b;// subtract b(3) from a(5) and assing to b(b = 2)a=a-b;// subtract b(2) from a(5) and assign to a(a = 3)console.log(a,b)// a = 3, b = 2
Random Number
//random number from 0-1;letrandomNumber=Math.round(Math.random());//random number from 0-6;randomNumber=Math.round(Math.random()*6)//random number from 1-10randomNumber=Math.floor(Math.random()*10)+1;//console.log(randomNumber);// 10 random number at a timefor(leti=1;i<=10;i++){randomNumber=Math.floor(Math.random()*10)+1;console.log(randomNumber);}constnum=2.1205;constfloorResult=Math.floor(num);constceilResult=Math.ceil(num);constroundResult=Math.round(num);//console.log(roundResult);
Maximum of 3 num
functionmax3Num(num1,num2,num3){letmax=num1;if(num2>max){max=num2;}if(num3>max){max=num3;}returnmax;}//console.log(max3Num(40, 50, 60));//using math objectconstmaxNumber=Math.max(5,34,30);console.log(maxNumber)
Largest number of array
// find the largest number of an arrayfunctionlargesNumOfArr(array){letlargestNum=array[0];for(leti=0;i<array.length;i++){letelement=array[i];if(element>largestNum){largestNum=element;}}returnlargestNum;}constmarks=[25,89,53,65];console.log(largesNumOfArr(marks));
Smallest number of an array
//find the smallest number of an arrayfunctionsmallestNumOfArr(array){letsmallestNum=array[0];for(leti=0;i<array.length;i++){letelement=array[i];if(element<smallestNum){smallestNum=element;}}returnsmallestNum;}constmarks=[25,89,15,65];console.log(smallestNumOfArr(marks));
//function of unique arrayfunctionuniqueArray(array){constnewArray=[];for(leti=0;i<array.length;i++){letelement=array[i];letindex=newArray.indexOf(element);if(index==-1){newArray.push(element);}}returnnewArray;}constticket=[1,2,3,3,4,5,2,6,7,7,9,4,10,2];constresult=uniqueArray(ticket);console.log(result);// an easy way using setconstuniqueArr2=[...newSet(ticket)]
Word count
// count the number of words in a stringfunctionwordCount(str){letcount=0;for(leti=0;i<str.length;i++){if(str[i]==' '){count++;}}count++;returncount;}letmyString='My name is Jisan. I am a programmer'//console.log(wordCount(myString));//another small solutionfunctioncountWord(str){// split method will spearte all the word by comma and turn the string into an array then we will get the lenght of the array using .lenght;returnstr.split(' ').length;}console.log(countWord(myString));//acurate wayfunctioncount_words(str){//exclude start and end white spacestr=str.replace(/(^\s*)|(\s*$)/gi,"");//convert 2 or more spaces to 1str=str.replace(/[]{2,}/gi," ");//exclude newline with a start spacingstr=str.replace(/\n/,"\n");returnstr.split(' ').length;;}myString="My name is Jisan."console.log(count_words(myString))
20. Different ways to reverse a string
```js
//reverse string with increement for loop
function reverseString(str) {
let reverse = ''
for (let i = 0; i < str.length; i++) {
let char = str[i];
reverse = char + reverse;
}
return reverse;
}
let myString = 'Reverse this string';
//console.log(reverseString(myString));
//reverse string with a decrementing for loop
function reverseString1(str) {
let reverse = ''
for (let i = str.length - 1; i >= 0; i--) {
let char = str[i];
reverse = reverse + char;
}
return reverse;
}
myString = 'Reverse';
//console.log(reverseString1(myString));
//using array
function reverseString2(str) {
if (!str || str.length < 2 || typeof str != 'string') {
return "Not Valid"
}
const revArray = [];
for (let i = str.length - 1; i >= 0; i--) {
revArray.push(str[i]);
}
return revArray.join('');
}
myString = 'Programmer';
console.log(reverseString2(myString))
//reverse a string using built-in function
function stringReverse(str) {
//use the split() mehtod to return a new array
let splitString = str.split("");
//use the reverse() mehod to revere the new creted array;
let reverseArray = splitString.reverse();
//use the join() mehod to join all elements of the array into string
let joinArray = reverseArray.join("");
return joinArray;
// we can do everything above in one line
// return str.split("").reverse().join("");
}
console.log(stringReverse(myString));
feet to mile
//feet to mileletmile;functionfeetToMile(feet){mile=feet/5200;returnmile;}constresult=feetToMile(6500);console.log(result)
check palindrome
conststring="level";// using built in functionsfunctionisPalindrme1(string){returnstring.split("").reverse().join("")==string;}console.log(isPalindrme1(string));// true// using for loopconstisPalindrome2=(string)=>{letstrLen=Math.floor(string.length/2);string=string.toLocaleLowerCase();for(leti=0;i<strLen;i++){if(string[i]!==string[strLen-i-1]){returnfalse;}}returntrue;};
check sim operator available in bangladesh
functioncheckPhoneNum(number){constregex=/(\+88)?-?01[1-9]\d{8}/g;if(regex.test(number)){if(/(\+88)?-?018\d{8}/g.test(number)){return"It's robi number";}elseif(/(\+88)?-?017\d{8}/g.test(number)){return"It's grameen number";}elseif(/(\+88)?-?019\d{8}/g.test(number)){return"It's banglalink number";}elseif(/(\+88)?-?016\d{8}/g.test(number)){return"It's airtle number";}return"There is no operator with this pattern";}else{return"Number is invalid";}}consttext="+8801901422927";// const regex = /(\+88)?-?01[1-9]\d{8}/g;constresult=checkPhoneNum(text);console.log(result);
functionstringToWordArr(string){if(typeofstring==="string"){returnstring.split(" ");}else{return"Enter valid input";}}consttext="My name is Jisan";constresult=stringToWordArr(text);console.log(result);
Array max sub sum
functiongetMaxSubSum(array){letmaxSubSum=0;for(leti=0;i<array.length;i++){letsumFixedStart=0;for(letj=i;j<array.length;j++){sumFixedStart+=array[j];maxSubSum=Math.max(maxSubSum,sumFixedStart);}}returnmaxSubSum;}constresult=getMaxSubSum([-1,2,3,-9,11]);// console.log(result);// optimzed solution in O(n)functiongetMaxSubSum2(array){letmaxSum=0;letpartialSum=0;for(letitemofarray){partialSum+=item;maxSum=Math.max(maxSum,partialSum);if(partialSum<0)partialSum=0;}returnmaxSum;}constresult1=getMaxSubSum2([-1,2,3,-9]);// console.log(result1);// solution 3functionsol3(arr){letsubSum=[];for(leti=0;i<arr.length;i++){letsum=0;for(letj=i;j<arr.length;j++){sum+=arr[j];subSum.push(sum);}}returnMath.max(...subSum);}console.log(sol3([-1,2,3,-9]));
Most used char in a string
// Write a function that takes a string, and returns the character that is most commonly used in the string.functiongetMostUsesChar(str){if(typeofstr=="string"){letcharCount={};letmostUseChar="";letmostUseCharCount=0;for(letcharofstr){charCount[char]=charCount[char] ? charCount[char]+1 : 1;}for(letkeyincharCount){// console.log(charCount[key]);if(charCount[key]>mostUseCharCount){mostUseCharCount=charCount[key];mostUseChar=key;}}returnmostUseChar;}return;}constresult=getMostUsesChar("Jisaan-mia");console.log(result);
remove duplicate from an array using reduce
// remove duplicate from an arrayconstarrWithDuplicates=[3,4,1,6,23,4,3,8,1];constuniqueArr=arrWithDuplicates.reduce((acc,currentValue)=>{if(acc.indexOf(currentValue)===-1){acc.push(currentValue);}returnacc;},[]);console.log(uniqueArr);
sort array of objects
// Given an array of objects, sort the objects by population size. Return the entire object.functionsortObj(arrOfObj){returnarrOfObj.sort((a,b)=>b.population-a.population);}constarrObj=[{country: "bd",population: 20},{country: "ca",population: 10},{country: "la",population: 6},{country: "ma",population: 100},];console.log(sortObj(arrObj));
Anagram
// Create a function that takes in two strings as two parameters and returns a boolean that indicates whether or not the first string is an anagram of the second string.// anagram: An anagram is another word or phrase formed by rearranging letters of the first word or phrase. eg.// Tar = Rat,// Night = Thing// Arc = Car// Elbow = Below// State = TastefunctionisAnagram(str1,str2){if(str1.length!=str2.length){returnfalse;}letsort1=str1.toLowerCase().split("").sort();letsort2=str2.toLowerCase().split("").sort();returnsort1.join("")==sort2.join("");}constresult=isAnagram("Tar","Rat");console.log(result);
Armstrong number
// An Armstrong number is an n-digit number that is equal to the sum of the nth powers of its digits. Determine if the input number is an Armstrong number. Return either true or false.// eg. 153, 370, 371, 407, 1634, 8208 etc. are armstrong number// 153 = 1³ + 5³ + 3³// 1634 = 1⁴ + 6⁴ + 3⁴ + 4⁴functionisArmstrong(number){constnumStr=number.toString();constlength=numStr.length;letsum=0;for(leti=0;i<length;i++){sum+=Math.pow(Number(numStr[i]),length);}returnsum==number;}constcheckArmstrong=isArmstrong(5);console.log(checkArmstrong);
character to ascii
// Create a function that will convert a string in an array containing the ASCII codes of each characterfunctiongetAsciiCode(str){constarrOfAscii=[];for(leti=0;i<str.length;i++){arrOfAscii.push(str.charCodeAt(i));}returnarrOfAscii;}console.log(getAsciiCode("My Name is Jisan"));
merge 2 array exclusive
// Create a function that will receive two arrays of numbers as arguments and return an array composed of all the numbers that are either in the first array or second array but not in bothfunctiongetUniqueOf2arr(arr1,arr2){letuniqueArr=[];// first filter out items from arr1 that is not in arr2uniqueArr=[...arr1.filter((num)=>!arr2.includes(num))];// second spread arr1 items after filtering then// do the same thing as we did to filter out in arr1 for arr2uniqueArr=[...uniqueArr, ...arr2.filter((num)=>!arr1.includes(num))];returnuniqueArr;}letarr1=[1,2,3,4,5];letarr2=[4,5,6,7,8,9,10];constresult=getUniqueOf2arr(arr1,arr2);console.log(result);// [1, 2, 3, 6, 7, 8, 9, 10]
factorial in recursive way
//factorial // 3! = 1X2X3// 4! = 1X2X3X4// 5! = 1X2X3X4X5//factorial using recursive function// 0! = 1// 2! = 1X2// 3! = 1X2X3 == 2! X 3// 4! = 1X2X3X4 == 3! X4// 5! = 1X2X3X4X5 == 4! X 5// 6! = (6-1)! X 6// 7! = (7-1)! X 7// n! = (n-1)! X nfunctionrecurFactorial(n){letfact;if(n==0){return1;}else{returnn*recurFactorial(n-1);}}console.log(recurFactorial(5));
/** * Given two sorted arrays array1 and array2 of size m and n respectively. * Find the median of the two sorted arrays. * * @Example 1: * Input: * m = 3, n = 4 * array1 = [1, 9, 15] * array2 = [2, 4, 5, 23] * * Output: 5 * * @Example 2: * Input: * m = 2, n = 4 * array1 = [41, 78] * array2 = [3, 4, 7, 8] * * Output: 7.5 * * Expected Time Complexity: O(min(log n, log m)). * Expected Auxiliary Space: O((n+m)/2). */
Bracket Mather
// Have the function bracketMather(str) take the str parameter being passed and return 1 if the brackets are correctly matched and each one is accounted for. Otherwise return 0functionbracketMather(str){letopen=0;for(leti=0;i<str.length;i++){if(str[i]==='(')open++;if(str[i]===')')open--;if(open<0)return0;}returnopen ? 0 : 1;}bracketMather('(a+b)(b-a))')// 0
anagram
functionisAnagram(first,second){// For case insensitivity, change both words to lowercase.vara=first.toLowerCase();varb=second.toLowerCase();// Sort the strings, and join the resulting array to a string. Compare the resultsa=a.split("").sort().join("");b=b.split("").sort().join("");returna===b;}
/*Problem: create a loop that execute from 1-100i) Every time you reach a multiple of 3(3, 6, 9 etc) you replace the number with the word "Fizz" or log "Fizz"ii) Every time you reach a multiple of 5(5, 10, 15, etc) you replace the number with "Buzz" or log "Buzz"iii) and if you reach a multiple of 3 AMD 5(15, 30, 46 etc) you replace the number with "FizzBuzz" of log "FizzBuz"iv) if any of the above condition isn't true then log the current number */functionnormalFizzBuzz(startNum,endNum){for(leti=startNum;i<=endNum;i++){if(i%3==0&&i%5==0){console.log("FizzBuzz");}elseif(i%3==0){console.log("Fizz");}elseif(i%5==0){console.log("Buzz");}else{console.log(i);}}}// normalFizzBuzz(1, 10);// solve this FizzBuzz question without using reminder % operatorfunctionisFloatNum(num){// console.log(num);returnnum.toString().includes(".");}functionwithoutRemFizzBuzz(startNum,endNum){for(leti=startNum;i<=endNum;i++){if(!isFloatNum(i/3)&&!isFloatNum(i/5)){console.log("FizzBuzz");}elseif(!isFloatNum(i/3)){console.log("Fizz");}elseif(!isFloatNum(i/5)){console.log("Buzz");}else{console.log(i);}}}// withoutRemFizzBuzz(1, 100);
remove falsy values from an array
// remove falsy value from an array// falsy values// false, 0 , ""(blank), null, undefined, NaN(Not a Number)constnumArrWithFalsyValues=[1,2,NaN,3,"",4,5,null,false];constnumsWithoutFalsyValues=numArrWithFalsyValues.filter(Boolean);console.log(numsWithoutFalsyValues);// [1, 2, 3, 4, 5]// Explanation// Boolean(expression) in javascript returns true or falseconsole.log(Boolean(2>3));// return true since 2 is getter than 3 and so it is true and also returns trueconsole.log(Boolean(45>50));// return false since 45 is not getter than 50 and so it is false and returns falseconsole.log(Boolean("Jisan"));// return true since 'Jisan' is not an falsy valueconsole.log(Boolean(""));// return true since ''(blank) is an falsy value
// input an string and return the counts of every word used othe that string// in an object, eg.varinputStr="Fear leads to anger ; anger leads to hatred ; hatred leads to conflict ; conflict leads to suffering"varexptedOutput={"Fear": 1,"leads": 4,"to": 4,"anger": 2,";": 3,"hatred": 2,"conflict": 2,"suffering": 1}constmutableApproach=str=>{letcountedWords={};str.split(" ").forEach((word)=>{if(countedWords[word]){countedWords[word]+=1;return;}countedWords[word]=1;})returncountedWords}constfunctionalApproach=str=>str.split(" ").reduce((acc,word)=>{if(acc[word]){return{...acc,[word]: acc[word]+1};}return{...acc,[word]: 1}},{})console.log(mutableApproach(inputStr));console.log(functionalApproach(inputStr));
isTwin
// check if two string has the characters/letters, could be ordered or unordered// eg "hello", "world" = false// "lambs", "balms" = true// "flow", "wolf" = true// "cat", "act" = trueconstisTwin=(str1,str2)=>{if(str1.length!==str2.length){returnfalse}constsortStr1=str1.toLowerCase().split('').sort();constsortStr2=str2.toLowerCase().split('').sort();returnsortStr1.join('')==sortStr2.join('');}console.log(isTwin('cat','act'))// true
Multiples of 3 or 5(codewars)
// We want our function to take a number and// then provide the sum of all the natural numbers below it,// which are multiples of either 3 or 5.functionsolution(number){letsum=0;for(leti=0;i<number;i++){if(i%3==0||i%5==0){sum=sum+i;continue;}elseif(i%5==0){sum=sum+i;continue;}else{continue;}}returnsum;}console.log(solution(100))// 2318
fibonacci even number sum
// find the sum of the even-valued termsfunctionfiboEvenSum(n){letresult=[0,1];for(leti=0;i<(n-1);i++){constsum=result[result.length-1]+result[result.length-2];result.push(sum)}constevenSum=result.filter(item=>item%2==0).reduce((acc,currentValue)=>acc+currentValue)returnevenSum;}console.log(fiboEvenSum(10))// 44
Sum all digits within an string
// sum of all digits that occur in a given string.functionsumDigitStrings(digitStr){letdigitSum=0;for(leti=0;i<digitStr.length;i++){if(!isNaN(digitStr[i])){digitSum+=Number(digitStr[i]);}}returndigitSum;}console.log(sumDigitStrings('wo123r4l5d'))// 15
sum of cubes
// return the sum of cubes of all integer from 1 to a given integerfunctionsumOfCubes(n){letcSums=0;for(leti=1;i<=n;i++){cSums+=Math.pow(i,3);}returncSums;}console.log(sumOfCubes(3))// 36
// Write a function that returns each number in the// array if it is larger than all the numbers to the// right or if it is the last valueconstvalues=[16,17,4,3,5,2];// should return [17, 5, 2]constresult=values.filter((value,idx)=>values.slice(idx+1).every(rightValue=>value>rightValue));console.log(result);