Minimum number of operations to convert a given sequence into a Geometric Progression | Javascript program to find minimum number of operations to convert a given sequence to an Geometric Progression ; Function to print the GP series ; Check for possibility ; Function for getting the Arithmetic Progression ; The array c describes all the given set of possible operations . ; Size of c ; candidate answer ; Loop through all the permutations of the first two elements . ; a1 and a2 are the candidate first two elements of the possible GP . ; temp stores the current answer , including the modification of the first two elements . ; Common ratio of the possible GP ; To check if the chosen set is valid , and id yes find the number of operations it takes . ; ai is value of a [ i ] according to the assumed first two elements a1 , a2 ith element of an GP = a1 * ( ( a2 - a1 ) ^ ( i - 1 ) ) ; Check for the " proposed " element to be only differing by one ; Set the temporary ans ; To infinity and break ; Update answer ; Calling function to print the sequence ; Array is 1 - indexed , with a [ 0 ] = 0 for the sake of simplicity ; Function to print the minimum operations and the sequence of elements
class pair { constructor ( first , second ) { this . first = first ; this . second = second ; } } function construct ( n , ans_pair ) { if ( ans_pair . first == - 1 ) { document . write ( " " ) ; return ; } var a1 = ans_pair . first ; var a2 = ans_pair . second ; var r = a2 / a1 ; document . write ( " " ) ; for ( var i = 1 ; i <= n ; i ++ ) { var ai = parseInt ( a1 * Math . pow ( r , i - 1 ) ) ; document . write ( ai + " " ) ; } } function findMinimumOperations ( a , n ) { var ans = 1000000000 ; var c = [ - 1 , 0 , 1 ] ; var possibilities = 3 ; var pos1 = - 1 , pos2 = - 1 ; for ( var i = 0 ; i < possibilities ; i ++ ) { for ( var j = 0 ; j < possibilities ; j ++ ) { var a1 = a [ 1 ] + c [ i ] ; var a2 = a [ 2 ] + c [ j ] ; var temp = ( Math . abs ( a1 - a [ 1 ] ) + Math . abs ( a2 - a [ 2 ] ) ) ; if ( a1 == 0 a2 == 0 ) continue ; var r = a2 / a1 ; for ( var pos = 3 ; pos <= n ; pos ++ ) { var ai = a1 * Math . pow ( r , pos - 1 ) ; if ( a [ pos ] == ai ) { continue ; } else if ( a [ pos ] + 1 == ai a [ pos ] - 1 == ai ) { temp ++ ; } else { temp = 1000000000 ; break ; } } if ( temp < ans ) { ans = temp ; pos1 = a1 ; pos2 = a2 ; } } } if ( ans == - 1 ) { document . write ( " " ) ; return ; } document . write ( " " + " " + ans + " " ) ; var ans_pair = new pair ( pos1 , pos2 ) ; construct ( n , ans_pair ) ; } var a = [ 0 , 7 , 20 , 49 , 125 ] ; var n = a . length ; findMinimumOperations ( a , n - 1 ) ;