Mathematical methods you don't know in JavaScript (very practical)

 Dachang interview questions share interview question bank

Front-end and back-end interview question banks (necessary for interviews) Recommended: ★★★★★

Address: front-end interview question bank   web front-end interview question bank VS java back-end interview question bank Daquan

JavaScript's Math object contains some very useful and powerful mathematical operations that can be used in web development, but it lacks many important operations that most other programming languages ​​provide (such as Haskell, which has a large number of such operations).

Here are quick links to each action:

  • Sum

  • Product

  • Odd and Even

  • triangleNumber

  • Factorial

  • Factors

  • isPrime

  • Greatest Common Divisor

  • Lowest Common Multiple

The missing math method in JavaScript: Sum (Sum)

You may remember that in school, "sum" was a synonym for "add". For example, if we sum the numbers 1, 2 and 3, we actually mean 1+2+3.

Our sum function will involve summing all the values ​​in the array.

There are two ways of writing this function: we can use a for loop, or we can use a reduce function. If you want to re-acquaint yourself with the reduce function, you can read the documentation on using map() and reduce() in JavaScript.

How to use for loop:

function sum(array){
    let total = 0
    for(let count = 0; count < array.length; count++){
        total = total + array[count]
    }
    return total
}

The way to use the reduce function:

function sum(array){
    return array.reduce((sum, number) => sum + number, 0)
}

Both functions work exactly the same way (the reduce function is just a built-in for loop) and will return the same result given the same array. However, the reduce function is more concise.

For example:

sum([1,2,3,4]) === 10 // 1 + 2 + 3 + 4

sum([2,4,6,8]) === 20 // 2 + 4 + 6 + 8

Being able to sum a set of numbers is probably the most useful and most requested "missing" math operation in the JavaScript Math object. Again, the sum function can be a good checking tool. For example, in Sudoku we can check that the user has no repeated numbers by checking if the sum of the column or row is 45 (1+2+3+4+…+9). This function would also work great in an online shopping application, if we want to calculate the total bill, assuming all prices are stored in an array.

Here is sample code of how to use this function in the shopping application example:

const prices = [2.80, 6.10, 1.50, 1.00, 8.99, 2.99]

function totalCost(prices){
    return prices.reduce((sum, item) => sum + item, 0)
}

The missing math method in JavaScript: Product

Our product function will work in a similar way to the sum function, except that we will multiply all the numbers in the list.

Likewise, we can use a for loop almost the same as the first sum function:

function product(array){
    let total = 1
    for(let count = 0; count < array.length; count++){
        total = total * array[count]
    }
    return total
}

Note that we initialize the total variable with 1, not 0, otherwise the resulting product will always be 0.

But in this case, the reduce function still applies, and is still a more concise way of writing functions:

function product(array){
    return array.reduce((total, num) => total*num, 1)
}

Here is some sample code:

product([2,5,8,6]) === 480 // 2 x 5 x 8 x 6

product([3,7,10,2]) === 420 // 3 x 7 x 10 x 2

The purpose of this function may not seem obvious, but it is very useful when doing calculations for multiple transformations. For example, if you want to find out the dollar price of ten bags of apples (1 kg each, selling for 1.50RMB), instead of doing a lot of multiplication, store all the values ​​in an array and use the product you just wrote function will be more efficient.

An example format for an array is as follows:

const pricePerKg = 1.50
const numberOfKg = 10
const conversionRate = 1.16
const conversion = [1.50, 10, 1.16]

const USprice = product([pricePerKg,numberOfKg,conversionRate])

Missing Math Methods in JavaScript: Odd and Even

These functions will take a number as an argument, which can be the length of the array, and return true or false depending on whether the number is odd or even.

To judge whether a number is even or not, it must be divisible by 2; and to judge whether a number is odd or not, on the contrary, it must not be divisible by 2. This will be the key part of the function.

For example, the Haskell language has these functions built in, which makes things much easier, especially since it is straightforward to write code like this:

even 29
<< false

odd 29
<< true

On the other hand, Ruby provides these functions as methods. It's still easier to write this way:

29.even?
<< false

29.odd?
<< true

In JavaScript, the easiest way to write these functions is to use the remainder operator %. It returns the remainder of dividing one number by another. For example:

11 % 3 === 2 // 11 divide 3 === 3 remainder 2

Here is an example of our even function:

function even(number){
    return number % 2 === 0
}

As we can see, we have an even function that accepts a number as an argument and returns a boolean value depending on the condition:

number % 2 === 0

When the number is divisible by 2, if the remainder equals zero, we know it is divisible by 2 and the function will return true. For example:

even(6) === true

even (9) === false

Here's an example of our odd function:

function odd(number){
    return number % 2 !== 0
}

These two functions are very similar: both accept a number as an argument and return a boolean value depending on the condition:

number % 2 !== 0

If the remainder of dividing a number by 2 is not equal to zero, then the number is odd and the function will return true. For example:

odd(7) === true

odd(114) === false

Being able to check whether a number is odd or even is very important and very simple. It might not seem that important at first, but it can be a good input validation technique, e.g. for array lengths, or simply by checking the winner of a two player game. You can keep track of how many rounds have been played, and if the number of rounds is odd, player 1 wins, if it's even, player 2 wins - assuming the first round counts as 1.

These two functions are used interchangeably, and we will most likely only need to use one or the other. However, having these two functions makes it easier to keep track of true and false logic in your code, especially in large chunks of code.

Here's how we would code the above example:

function checkWinner(gamesPlayed){
    let winner
    if(odd(gamesPlayed)){
        winner = "player1"
    }
    else{
        winner = "player2"
    }
    return winner
}

The missing math method in JavaScript: Triangle Number

Triangular numbers sound more complicated than they actually are. They are simply the sum of all integers preceding a certain number.

For example, here's the fifth triangular number: 5 + 4 + 3 + 2 + 1 = 15.

This is related to the Sudoku example we mentioned earlier. We want to check if all numbers are unique and we can do this by checking if they are equal to the result of 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9. This is of course the ninth triangular number!

Of course, we could write this function using a for loop, like this:

function triangleNumber(number){
    let sum = 0
    for(let i=1; i < number + 1; i++){
        sum = sum + i
    }
    return sum
}

However, this would be a very inefficient decision, since there is a very simple formula for computing trigonometric numbers: 0.5 x (number) x (number + 1).

Therefore, the most efficient version of our function should look like this:

function triangleNumber(number){
    return 0.5 * number * (number + 1)
}

Here's some sample code of how we use it:

triangleNumber(7) === 28 // 0.5 x 7 x 8

triangleNumber(123) === 7626 // 0.5 x 123 x 124

The missing math method in JavaScript: Factorial

The factorial of a natural number (any integer greater than 0) is the product of all numbers less than or equal to that number. For example: the factorial of 3 (represented as 3!) is 3 x 2 x 1 = 6.

Similar to the summation and product functions, we can create the factorial function in two ways: using a for loop and using recursion. If you haven't been exposed to recursive algorithms before, they are essentially functions that repeatedly call themselves until a "base case" is reached. You can read more about them in Recursion in Functional JavaScript.

Here is how we create the factorial function using a for loop:

function factorial(number){
  let total = 1
  for (let i = 1; i < number+1; i++){
    total = total * i
  }
  return total
}

The function loops through the numbers given from 1 to the given number (incrementing each time) and multiplies the total with each number, finally returning the final total (that is, the factorial of that number).

Here is how we create the factorial function using recursion:

function factorial(number){
  if (number <= 0){
    return 1
  }
  else{
    return number * factorial(number - 1)
  }
}

In this function, our base case is 0, because the factorial of 0 is surprisingly 1 (this proof is actually quite interesting). This means that when the number is passed through the function, it will be multiplied by factorial(number - 1) as long as it is not zero.

To better understand exactly what the function does on each pass, it may be helpful to trace the algorithm. Here is an example using the 3 tracking algorithm:

factorial(3) === 3*factorial(2) === 3*2*factorial(1) === 3*2*1*factorial(0) === 3*2*1*1 === 3*2*1 === 6

Either way, both functions return the same value. For example:

factorial(5) === 120 // 5 x 4 x 3 x 2 x 1

The missing math method in JavaScript: Factors

The factors come in pairs, and each pair of factors is multiplied to get the original number. For example:

  • The factors of the number 10 are: 1 and 10; 2 and 5.

  • The factors of the number 18 are: 1 and 18; 2 and 9; 3 and 6.

We want our factor function to take a number and return an array containing all factors. There are many ways to write this function, but the easiest way is to use an imperative approach, such as this:

function factors(number){
    let factorsList = []
    for(let count = 1; count < number+1; count++){
        if(number % count === 0){
            factorsList.push(count)
        }
    }
    return factorsList
}

First, we create an array, initially empty. Then we use a for loop to iterate through each integer from 1 to the given number, and each time through we check if the number is divisible by an integer (or a counter in this case).

As you can see, to check for divisibility, we use the modulo operator again. If a number is divisible by an integer, it is a factor and can be added to our array.

This array is then returned, and each time the function is run, an array of factors in ascending order is returned. For example:

factors(50) === [1,2,5,10,25,50]

Finding a factor of a number is very useful in many situations, especially when you need to organize groups, such as in online games, when you need each team to have an equal number of players. For example, if you have 20 players and each team needs 10 players, you can use the factor function to divide the 10 players between the two teams. Likewise, if each team needs 4 players, you can use the factor function to distribute the 4 players among the five teams.

In a practical application, it might look like this:

function createTeams(numberOfPlayers, numberOfTeams){
    let playersInEachTeam
    if(factors(numberOfPlayers).includes(numberOfTeams)){
        playersInEachTeam = numberOfPlayers / numberOfTeams
    }
    else{
        playersInEachTeam = "wait for more players"
    }
    return playersInEachTeam
}

The missing math method in JavaScript: isPrime (is prime)

This is one of the earliest conditions learned in school, but is rarely used in everyday life. In short, a number is prime if it has two distinct factors that are 1 and itself. The prime numbers start at 2: 2, 3, 5, 7, 11, 13, 17, 19... and go on to infinity.

This function might look complicated at first, but it's actually quite simple if we've just written a very useful factor function. As mentioned earlier, a number is prime if it has two distinct factors, so our function can simply be written as:

function isPrime(number){
    return factors(number).length === 2
}

The function will return a boolean based on whether the factor list has length 2, in other words it will return whether the number has two factors.

In practice, it would look like this:

isPrime(3) === true

isPrime(76) === false

isPrime(57) === true

Continuing on from the "group users" example above, if the number of users is a prime number, we cannot group evenly (unless we only have one group, but that defeats the purpose of the example), which means we have to wait for another user to join. Therefore, we can use it in a function like this:

function addUsers(users){
    if(isPrime(users)){
        wait = true
    }
    else{
        wait = false
    }
}

The missing math method in JavaScript: gcd (Greatest Common Divisor)

Sometimes called "highest common factor", the greatest common divisor operation finds the largest factor that two numbers have in common.

For example:

  • The greatest common divisor of 12 and 15 is 3

  • The greatest common divisor of 8 and 4 is 4.

An easy way to do this is to list all the factors of each number (using the incredible function mentioned above), then compare the lists. However, comparing these lists requires some clever but not very efficient array operations.

Still, here's an example:

function gcd(number1, number2){
    let inCommon = []
    for(let i of factors(number1)){
        if(factors(number2).includes(i)){
            inCommon.push(i)
        }
    }
    return inCommon.sort((a,b)=> b - a)[0]
}

Here, we assign an empty array to the variable inCommon and loop through the array of factors of number1 (using the previous function). If number2's factor array contains the currently traversed item, we push it into the inCommon array.

Once we have an array of factors common to both numbers, we return the first value in the array sorted in descending order. In other words, we return the greatest common divisor.

As you can imagine, this code would be huge if we didn't have the factors function we created earlier.

A cleaner but harder way is to use recursion. Here's a fairly well-known algorithm known as Euclid's Algorithm:

function gcd(number1, number2){
    if(number2 === 0){
        return number1
    }
    else{
        return gcd(number2, number1%number2)
    }
}

Our basic situation is when number2 is equal to 0, then number1 is the greatest common divisor. Otherwise, the greatest common divisor is the greatest common divisor of number2 and the remainder of number1 divided by number2.

Again, both functions return the same result. For example:

gcd(24, 16) === 8

gcd(75, 1) === 1

The least common multiple (LCM) is to find the smallest positive integer that can be divided by two or more numbers.

For example:

The least common multiple of 2 and 6 is 6. The least common multiple of 4 and 15 is 60. Unfortunately, we cannot simply enumerate all the multiples of each number, as this would be an infinite list.

However, we can use a very useful formula to calculate the least common multiple:

(number1 x number2) / the Greatest Common Divisor of the two numbers

The steps to calculate the least common multiple (LCM) of 2 and 6 using the formula are as follows:

  1. Find the greatest common divisor (GCD) of two numbers. In this case, the greatest common divisor of 2 and 6 is 2.
  2. Multiply two numbers and divide by their greatest common divisor. In this case, 2 times 6 divided by 2 equals 6.

Therefore, the least common multiple (LCM) of 2 and 6 is 6.

(2 x 6)/gcd(2,6) = 12/2 = 6

Luckily, we just created a gcdfunction, so creating lcma function is easy:

function lcm(number1, number2){
    return (number1*number2)/gcd(number1, number2)
}

that's all! We just need to return the above formula and it should work fine:

lcm(12, 9) === 36 // (12 x 9)/3

There may be no obvious practical use for this function, but I often find it very useful when two events occur at different intervals. This means we can use the Least Common Multiple (LCM) to find out when two events occur at the same time.

For example, if an image is set to appear every six seconds and a paragraph of text is set to appear every eight seconds, at 24 seconds the image and paragraph will appear together for the first time.

Dachang interview questions share interview question bank

Front-end and back-end interview question banks (necessary for interviews) Recommended: ★★★★★

Address: front-end interview question bank   

web front-end interview question bank VS java back-end interview question bank Daquan

Guess you like

Origin blog.csdn.net/weixin_42981560/article/details/131522185