Counting possible APs within an array in JavaScript


Arithmetic Progression

Arithmetic Progression (AP) is a sequence of numbers such that the difference of any two consecutive numbers is a constant value (aka common difference).

For instance, 1, 2, 3, 4, 5, 6,… is an AP, which has a common difference equal to 1 (2 -1).

Problem

We are required to write a JavaScript function that takes in an array of integers, arr, as the first and the only argument.

The task of our function is to return the number of arithmetic progressions of size 3 that are possible from that list. In each progression, the differences between the elements must be the same. We are guaranteed 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 desired APs are −

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

Example

Following is the code −

 Live Demo

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

Updated on: 22-Apr-2021

64 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements