Modify array by replacing elements with the nearest power of its previous or next element | Function to calculate the power of y which is nearest to x ; Base Case ; Stores the logarithmic value of x with base y ; Function to replace each array element by the nearest power of its previous or next element ; Stores the previous and next element ; Traverse the array ; Calculate nearest power for previous and next elements ; Replacing the array values ; Print the updated array ; Given array
function nearestPow ( x , y ) { if ( y == 1 ) return 1 var k = Math . floor ( Math . log ( x ) / Math . log ( y ) ) if ( Math . abs ( Math . pow ( y , k ) - x ) < Math . abs ( Math . pow ( y , ( k + 1 ) ) - x ) ) return Math . pow ( y , k ) return Math . pow ( y , ( k + 1 ) ) } function replacebyNearestPower ( arr ) { var prev = arr [ arr . length - 1 ] var lastNext = arr [ 0 ] for ( var i = 0 ; i < arr . length ; i ++ ) { var temp = arr [ i ] if ( i == arr . length - 1 ) var next = lastNext else var next = arr [ ( i + 1 ) % arr . length ] var prevPow = nearestPow ( arr [ i ] , prev ) var nextPow = nearestPow ( arr [ i ] , next ) if ( Math . abs ( arr [ i ] - prevPow ) < Math . abs ( arr [ i ] - nextPow ) ) arr [ i ] = prevPow else arr [ i ] = nextPow prev = temp } document . write ( arr ) } var arr = [ 2 , 3 , 4 , 1 , 2 ] replacebyNearestPower ( arr )