Modify array by replacing elements with the nearest power of its previous or next element | C # program for the above approach ; 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 ; Driver Code ; Given array
using System ; class GFG { static int nearestPow ( int x , int y ) { if ( y == 1 ) return 1 ; int k = ( int ) ( Math . Log ( x , y ) ) ; if ( Math . Abs ( Math . Pow ( y , k ) - x ) < Math . Abs ( Math . Pow ( y , ( k + 1 ) ) - x ) ) return ( int ) ( Math . Pow ( y , k ) ) ; return ( int ) ( Math . Pow ( y , ( k + 1 ) ) ) ; } static void replacebyNearestPower ( int [ ] arr ) { int prev = arr [ arr . Length - 1 ] ; int lastNext = arr [ 0 ] ; int next = 0 ; for ( int i = 0 ; i < arr . Length ; i ++ ) { int temp = arr [ i ] ; if ( i == arr . Length - 1 ) next = lastNext ; else next = arr [ ( i + 1 ) % arr . Length ] ; int prevPow = nearestPow ( arr [ i ] , prev ) ; int 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 ; } for ( int i = 0 ; i < arr . Length ; i ++ ) Console . Write ( arr [ i ] + " ▁ " ) ; } public static void Main ( ) { int [ ] arr = { 2 , 3 , 4 , 1 , 2 } ; replacebyNearestPower ( arr ) ; } }