Freecodecamp JavaScript elementary algorithm question-1

1. Convert degrees Celsius to degrees Fahrenheit
The conversion from Celsius to Fahrenheit is calculated by multiplying Celsius by 9 / 5 and then adding 32
Input: convertToF(0) should return a number
Input: - 30
Output: - 22
Where celsius stands for celsius and fahrenheit for fahrenheit
Solution:

function convertToF(celsius) {
  let fahrenheit;
  fahrenheit = (celsius*9/5)+32
  return fahrenheit;
}

Idea: this question is very simple. Just follow the formula set directly.

2. Reverse string
Invert the string passed into the function, and the return result of the function should also be a string
Solution:

function reverseString(str) {
  let temp = str.split('');
  temp = temp.reverse().join('');
  return temp;
}
reverseString("hello");

Idea: when you see this question, you first think of the method of reversing arrays in js, reverse(),
① Convert the string into an array and use the split method;
② Use the reverse method of the array to reverse the array elements
③ Use the join method to convert the array into a string (the title requires a string to be returned)
Knowledge points: split, join, reverse.

3. Calculates the factorial of an integer
Returns the factorial result of a given integer. For integer n, the factorial of n is the product of all positive integers less than or equal to n.
Factorials are usually signed n! To show.
For example: 5= 1 2 3 4 5 = 120

Solution 1:
function factorialize(num) {
  let product = 1;
  for (let i = 2; i <= num; i++) {
    product *= i;
  }
  return product;
}

Idea: it's easy to understand what factorial is, that is, multiply from 1 to num, then the initial traversal is 1, the cycle starts from 2 to num, and then multiply in turn.
Solution 2:

function factorialize(num) {
  if (num === 0) {
    return 1;
  }
  return num * factorialize(num - 1);
}

Idea: using the idea of recursion, call the functions successively until num=1,
Solution 3:

function factorialize(num) {
  return num < 0 ? 1 :
    new Array(num)
      .fill(undefined)
      .reduce((product, _, index) => product * (index + 1), 1);
}

Idea:
In this solution, the ternary operator and two methods (fill and reduce) are used. Fill means to fill the array. Reduce syntax:
arr.reduce(function(prev,cur,index,arr){
...
}, init);
Among them,
arr represents the original array;
prev represents the return value of the last callback call, or the initial value init;
cur represents the array element currently being processed;
Index indicates the index of the array element currently being processed. If the init value is provided, the index is 0; otherwise, the index is 1;
init represents the initial value.

4. Find the longest word in the string
Returns the length of the longest word in a given sentence.
The return value of the function should be a number.
Input: findLongestWordLength("The quick brown fox jumped over the lazy dog")
Output: 6
Input: findlongestwordlength ("what if we try a super long word such as OTORHINOLOGY")
Output: 19
Solution 1:

function findLongestWordLength(str) {
  let arr = str.split(' ');
  let len = [];
  for(let i =0;i<arr.length;i++){
    len.push(arr[i].length);
  }
   let MaxLen = Math.max(...len);

  return MaxLen;
}
findLongestWordLength("The quick brown fox jumped over the lazy dog");

Idea:
① Split the string into arrays with spaces as separators;
② Create a new array
④ Traverse the array and store the length of each word in the new array
⑤ Finally, compare the maximum number in the array

Knowledge points:
① Methods for converting arrays and strings to each other: split, join
② Calculate the maximum value of a set of parameters, math Max (parameter), the array should be written as math Max (... Array name)

Solution 2:

function findLongestWordLength(str) {
  let maxLen = 0;
  let arr = [];
  let right = 0,left = 0;
  for(let i =0;i<str.length;i++){
    if(str[i] == ' ') {
      right = i-left;
      left = i+1;
      arr.push(right)
    }
    if(i==str.length-1 && str[left-1] ==' '){
      right = str.length-left;
      arr.push(right)
    }
  }
  maxLen = Math.max(...arr);
  return maxLen;
}

Idea: sliding window idea
① Create two indexes: left and right. maxLen is responsible for recording the length and the new array arr
② Traverse the string. If a space is encountered, it will be determined as a word. Use right to record the size of the word and put the length in the array.
③ This algorithm needs to consider a case, because there is no space at the end of the last word, so the second if comes. If it traverses the last character and the space led out by left-1, it will be expressed as a word, calculate the size and put it into the array
③ Compare the size of the numbers in the new array, and the largest is the length of the longest word

Knowledge points:
① Sliding window idea
② Calculate the maximum value of a set of parameters, math Max (parameter), the array should be written as math Max (... Array name)
Record it here for the time being.

Keywords: Javascript Algorithm

Added by 990805 on Sun, 30 Jan 2022 22:41:52 +0200