Check if elements of array can be arranged in AP , GP or HP | Java 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
import java . util . * ; class GFG { static boolean checkIsAP ( double arr [ ] , int n ) { if ( n == 1 ) return true ; Arrays . sort ( arr ) ; double d = arr [ 1 ] - arr [ 0 ] ; for ( int i = 2 ; i < n ; i ++ ) { if ( arr [ i ] - arr [ i - 1 ] != d ) { return false ; } } return true ; } static boolean checkIsGP ( double arr [ ] , int n ) { if ( n == 1 ) return true ; Arrays . sort ( arr ) ; double r = arr [ 1 ] / arr [ 0 ] ; for ( int i = 2 ; i < n ; i ++ ) { if ( arr [ i ] / arr [ i - 1 ] != r ) return false ; } return true ; } static boolean checkIsHP ( double arr [ ] , int n ) { if ( n == 1 ) { return true ; } double [ ] rec = new double [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { rec [ i ] = ( ( 1 / arr [ i ] ) ) ; } if ( checkIsAP ( rec , n ) ) return true ; else return false ; } public static void main ( String [ ] args ) { double arr [ ] = { 1.0 / 5.0 , 1.0 / 10.0 , 1.0 / 15.0 , 1.0 / 20.0 } ; int n = arr . length ; int flag = 0 ; if ( checkIsAP ( arr , n ) ) { System . out . print ( " Yes , ▁ An ▁ AP ▁ can ▁ be ▁ formed " + "NEW_LINE"); flag = 1 ; } if ( checkIsGP ( arr , n ) ) { System . out . print ( " Yes , ▁ A ▁ GP ▁ can ▁ be ▁ formed " + "NEW_LINE"); flag = 1 ; } if ( checkIsHP ( arr , n ) ) { System . out . print ( " Yes , ▁ A ▁ HP ▁ can ▁ be ▁ formed " + "NEW_LINE"); flag = 1 ; } else if ( flag == 0 ) { System . out . print ( " No " ) ; } } }