Check if elements of array can be arranged in AP , GP or HP | C ++ program to check if a given array form AP , GP or HP ; Returns true if arr [ 0. . n - 1 ] can form AP ; Base Case ; Sort array ; After sorting , difference between consecutive elements must be same . ; Traverse the given array and check if the difference between ith element and ( i - 1 ) th element is same or not ; Returns true if arr [ 0. . n - 1 ] can form GP ; Base Case ; Sort array ; After sorting , common ratio between consecutive elements must be same . ; Traverse the given array and check if the common ratio between ith element and ( i - 1 ) th element is same or not ; Returns true if arr [ 0. . n - 1 ] can form HP ; Base Case ; Find reciprocal of arr [ ] ; After finding reciprocal , check if the reciprocal is in A . P . To check for A . P . ; Driver 's Code ; Function to check AP ; Function to check GP ; Function to check HP
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkIsAP ( double arr [ ] , int n ) { if ( n == 1 ) return true ; sort ( arr , arr + n ) ; double d = arr [ 1 ] - arr [ 0 ] ; for ( int i = 2 ; i < n ; i ++ ) { if ( arr [ i ] - arr [ i - 1 ] != d ) { return false ; } } return true ; } bool checkIsGP ( double arr [ ] , int n ) { if ( n == 1 ) return true ; sort ( arr , arr + n ) ; double r = arr [ 1 ] / arr [ 0 ] ; for ( int i = 2 ; i < n ; i ++ ) { if ( arr [ i ] / arr [ i - 1 ] != r ) return false ; } return true ; } bool checkIsHP ( double arr [ ] , int n ) { if ( n == 1 ) { return true ; } double rec [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { rec [ i ] = ( ( 1 / arr [ i ] ) ) ; } if ( checkIsAP ( rec , n ) ) return true ; else return false ; } int main ( ) { double arr [ ] = { 1.0 / 5.0 , 1.0 / 10.0 , 1.0 / 15.0 , 1.0 / 20.0 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int flag = 0 ; if ( checkIsAP ( arr , n ) ) { cout << " Yes , ▁ An ▁ AP ▁ can ▁ be ▁ formed " << endl ; flag = 1 ; } if ( checkIsGP ( arr , n ) ) { cout << " Yes , ▁ A ▁ GP ▁ can ▁ be ▁ formed " << endl ; flag = 1 ; } if ( checkIsHP ( arr , n ) ) { cout << " Yes , ▁ A ▁ HP ▁ can ▁ be ▁ formed " << endl ; flag = 1 ; } else if ( flag == 0 ) { cout << " No " ; } return 0 ; }