Home  >  Article  >  Web Front-end  >  Calculate possible arithmetic sequences in an array in JavaScript

Calculate possible arithmetic sequences in an array in JavaScript

王林
王林forward
2023-08-23 14:42:46907browse

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];

output

const output = 5;

Output explanation

Because the required AP is −

[1, 2, 3], [1, 3, 5], [1, 5, 9], [3, 5, 7] and [5, 7, 9]

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));

Output

5

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete