Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

This repository contains JavaScript based examples that will teach you the fundamentals of algorithmic thinking by writing functions that do everything from converting temperatures to handling complex 2D arrays.

NotificationsYou must be signed in to change notification settings

Adrinlol/JavaScript-Algorithms-and-Data-Structures

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

26 Commits
 
 

Repository files navigation

An algorithm is a series of step-by-step instructions that describe how to do something.

To write an effective algorithm, it helps to break a problem down into smaller parts and think carefully about how to solve each part with code.

This repository contains JavaScript based examples that will teach you the fundamentals of algorithmic thinking by writing functions that do everything from converting temperatures to handling complex 2D arrays.

All of these examples are from FreeCodeCamp'scourse.

Table of Contents

Basic Algorithm Scripting

1. Convert Celsius to Fahrenheit

Difficulty: Beginner

The algorithm to convert from Celsius to Fahrenheit is the temperature in Celsius times 9/5, plus 32.

You are given a variable celsius representing a temperature in Celsius. Use the variable fahrenheit already defined and assign it the Fahrenheit temperature equivalent to the given Celsius temperature. Use the algorithm mentioned above to help convert the Celsius temperature to Fahrenheit.


Solution

functionconvertToF(celsius){letfahrenheit=(celsius*9)/5+32;returnfahrenheit;}convertToF(30);

2. Reverse a String

Difficulty: Beginner

Reverse the provided string.

You may need to turn the string into an array before you can reverse it.

Your result must be a string.


Solution 1

functionreverseString(str){returnstr.split("").reverse().join("");}reverseString("hello");

Solution 2

functionreverseString(str){letreversedString="";for(leti=str.length-1;i>=0;i--){reversedString+=str[i];}returnreversedString;}reverseString("hello");

3. Factorialize a Number

Difficulty: Beginner

Return the factorial of the provided integer.

If the integer is represented with the letter n, a factorial is the product of all positive integers less than or equal to n.

Factorials are often represented with the shorthand notation n!

For example: 5! = 1 _ 2 _ 3 _ 4 _ 5 = 120

Only integers greater than or equal to zero will be supplied to the function.


Solution 1

functionfactorialize(num){if(num===0){return1;}elsereturnnum*factorialize(num-1);}factorialize(5);

Solution 2

functionfactorialize(num){letfactorializedNumber=1;for(leti=2;i<=num;i++){factorializedNumber*=i;}returnfactorializedNumber;}factorialize(5);

4. Find the Longest Word in a String

Difficulty: Beginner

Return the length of the longest word in the provided sentence.

Your response should be a number.


Solution

functionfindLongestWordLength(str){letsplitWords=str.split(" ");letlongestWordLength=0;for(leti=0;i<splitWords.length;i++){if(splitWords[i].length>longestWordLength){longestWordLength=splitWords[i].length;}}returnlongestWordLength;}findLongestWordLength("The quick brown fox jumped over the lazy dog");

5. Return Largest Numbers in Arrays Passed

Difficulty: Beginner

Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays.

Remember, you can iterate through an array with a simple for loop, and access each member with array syntax arr[i].

Solution 1

functionlargestOfFour(arr){letresults=[];for(leti=0;i<arr.length;i++){letlargestNumber=arr[i][0];for(letj=1;j<arr[i].length;j++){if(arr[i][j]>largestNumber){largestNumber=arr[i][j];}}results[i]=largestNumber;}returnresults;}largestOfFour([[4,5,1,3],[13,27,18,26],[32,35,37,39],[1000,1001,857,1],]);

Solution 2

functionlargestOfFour(arr){letresults=[];arr.forEach((elements)=>{letlargestNumber=elements[0];elements.forEach((item)=>{item>largestNumber&&(largestNumber=item);});results.push(largestNumber);});returnresults;}largestOfFour([[4,5,1,3],[13,27,18,26],[32,35,37,39],[1000,1001,857,1],]);

6. Confirm the Ending Passed

Difficulty: Beginner

Check if a string (first argument, str) ends with the given target string (second argument, target).

This challenge can be solved with the .endsWith() method, which was introduced in ES2015. But for the purpose of this challenge, we would like you to use one of the JavaScript substring methods instead.


Solution

functionconfirmEnding(str,target){returntarget===str.substr(-target.length);}confirmEnding("Bastian","n");

7. Repeat a String

Difficulty: Beginner

Repeat a given string str (first argument) for num times (second argument). Return an empty string if num is not a positive number. For the purpose of this challenge, do not use the built-in .repeat() method.


Solution 1

functionrepeatStringNumTimes(str,num){if(num<1){return"";}else{letstring=str;for(leti=1;i<num;i++){string+=str;}returnstring;}}repeatStringNumTimes("abc",3);

Solution 2

functionrepeatStringNumTimes(str,num){if(num<1){return"";}else{returnstr+repeatStringNumTimes(str,num-1);}}

8. Truncate a String

Difficulty: Beginner

Truncate a string (first argument) if it is longer than the given maximum string length (second argument). Return the truncated string with a ... ending.


Solution

functiontruncateString(str,num){if(str.length>num){returnstr.slice(0,num)+"...";}else{returnstr;}}truncateString("A-tisket a-tasket A green and yellow basket",8);

9. Finders Keepers

Difficulty: Beginner

Create a function that looks through an array arr and returns the first element in it that passes a 'truth test'. This means that given an element x, the 'truth test' is passed if func(x) is true. If no element passes the test, return undefined.


Solution 1

functionfindElement(arr,func){letnum=0;for(leti=0;i<arr.length;i++){num=arr[i];if(func(num)){returnnum;}}returnundefined;}findElement([1,2,3,4],(num)=>num%2===0);

Solution 2

functionfindElement(arr,func){returnarr.find(func);}findElement([1,2,3,4],(num)=>num%2===0);

10. Boo who

Difficulty: Beginner

Check if a value is classified as a boolean primitive. Return true or false.

Boolean primitives are true and false.


Solution 1

functionbooWho(bool){returntypeofbool==="boolean";}booWho(null);

11. Title Case a Sentence

Difficulty: Beginner

Return the provided string with the first letter of each word capitalized. Make sure the rest of the word is in lower case.

For the purpose of this exercise, you should also capitalize connecting words like the and of.


Solution 1

functiontitleCase(str){letconvertToArray=str.toLowerCase().split(" ");for(leti=0;i<convertToArray.length;i++){convertToArray[i]=convertToArray[i].charAt(0).toUpperCase()+convertToArray[i].slice(1);}returnconvertToArray.join(" ");}titleCase("I'm a little tea pot");

Solution 2

functiontitleCase(str){letconvertToArray=str.toLowerCase().split(" ");returnconvertToArray.map((item)=>{returnitem.replace(item.charAt(0),item.charAt(0).toUpperCase());}).join(" ");}titleCase("I'm a little tea pot");

12. Slice and Splice

Difficulty: Beginner

You are given two arrays and an index.

Copy each element of the first array into the second array, in order.

Begin inserting elements at index n of the second array.

Return the resulting array. The input arrays should remain the same after the function runs.


Solution

functionfrankenSplice(arr1,arr2,n){letlocalArr=[...arr2];localArr.splice(n,0, ...arr1);returnlocalArr;}frankenSplice([1,2,3],[4,5],1);

13. Falsy Bouncer

Difficulty: Beginner

Remove all falsy values from an array.

Falsy values in JavaScript are false, null, 0, "", undefined, and NaN.

Hint: Try converting each value to a Boolean.


Solution 1

functionbouncer(arr){returnarr.filter(Boolean);}bouncer([7,"ate","",false,9]);

Solution 2

functionbouncer(arr){letnewArray=[];for(leti=0;i<arr.length;i++){arr[i]&&newArray.push(arr[i]);}returnnewArray;}bouncer([7,"ate","",false,9]);

14. Where do I Belong

Difficulty: Beginner

Return the lowest index at which a value (second argument) should be inserted into an array (first argument) once it has been sorted. The returned value should be a number.

For example, getIndexToIns([1,2,3,4], 1.5) should return 1 because it is greater than 1 (index 0), but less than 2 (index 1).

Likewise, getIndexToIns([20,3,5], 19) should return 2 because once the array has been sorted it will look like [3,5,20] and 19 is less than 20 (index 2) and greater than 5 (index 1).


Solution 1

functiongetIndexToIns(arr,num){arr.sort((a,b)=>a-b);for(leti=0;i<arr.length;i++){if(arr[i]>=num)returni;}returnarr.length;}getIndexToIns([10,20,30,40,50],35);

Solution 2

functiongetIndexToIns(arr,num){returnarr.filter((val)=>num>val).length;}getIndexToIns([10,20,30,40,50],35);

15. Mutations

Difficulty: Beginner

Returntrue if the string in the first element of the array contains all of the letters of the string in the second element of the array.

For example, ["hello", "Hello"], should returntrue because all of the letters in the second string are present in the first, ignoring case.

The arguments["hello", "hey"] should returnfalse because the stringhello does not contain ay.

Lastly,["Alien", "line"], should returntrue because all of the letters inline are present inAlien.


Solution

functionmutation(arr){constarr1=arr[0].toLowerCase().split("");constarr2=arr[1].toLowerCase().split("");for(leti=0;i<arr2.length;i++){if(arr1.indexOf(arr2[i])==-1){returnfalse;}}returntrue;}mutation(["hello","hey"]);

About

This repository contains JavaScript based examples that will teach you the fundamentals of algorithmic thinking by writing functions that do everything from converting temperatures to handling complex 2D arrays.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp