Home > Web Front-end > JS Tutorial > body text

Calculate possible arithmetic sequences in an array in JavaScript

王林
Release: 2023-08-23 14:42:46
forward
864 people have browsed it

Calculate possible arithmetic sequences in an array in JavaScript

Arithmetic sequence

Arithmetic sequence (AP) is a sequence in which the difference between any two numbers is the same. Consecutive numbers are a constant value (also called a tolerance).

For example, 1, 2, 3, 4, 5, 6... is an arithmetic sequence with a tolerance equal to 1 (2-1).

Question

We need to write a JavaScript function that passes in an integer array arr as the first parameter And the only parameter.

The task of our function is to return the number of arithmetic sequences of size 3 Possibly choose from that list. In each process, the difference between elements must be same. We guarantee that the input array will be sorted in increasing order. For example, if The input to the function is

For example, if the input to the function is −

input

const arr = [1, 2, 3, 5, 7, 9];
Copy after login

output

const output = 5;
Copy after login

Output explanation

Because the required AP is −

[1, 2, 3], [1, 3, 5], [1, 5, 9], [3, 5, 7] and [5, 7, 9]
Copy after login

Example

The following is the code−

Real-time demonstration

const arr = [1, 2, 3, 5, 7, 9];
const countAP = (arr = []) => {
   let i, j, k;
   let { length: len } = arr;
   let count = 0;
   for (i = 0; i < len - 2; i++){
      for (k = i + 2; k < len; k++){
         let temp = arr[i] + arr[k];
         let div = temp / 2;
         if ((div * 2) == temp){
            for (j = i + 1; j < k; j++){
               if (arr[j] == div){
                  count += 1;
               }
            }
         }
      }
   }
   return count;
};
console.log(countAP(arr));
Copy after login

Output

5
Copy after login

The above is the detailed content of Calculate possible arithmetic sequences in an array in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!