Find initial sequence that produces a given Array by cyclic increments upto index P | Function to generate and return the required initial arrangement ; Store the minimum element in the array ; Store the number of increments ; Subtract mi - 1 from every index ; Start from the last index which had been incremented ; Stores the index chosen to distribute its element ; Traverse the array cyclically and find the index whose element was distributed ; If any index has its value reduced to 0 ; Index whose element was distributed ; Store the number of increments at the starting index ; Print the original array ; Driver Code
function findArray ( a , n , P ) { let mi = Math . min ( ... a ) ; let ctr = 0 ; mi = Math . max ( 0 , mi - 1 ) ; for ( let i = 0 ; i < n ; i ++ ) { a [ i ] -= mi ; ctr += mi ; } let i = P - 1 ; let start = - 1 ; while ( true ) { if ( a [ i ] == 0 ) { start = i ; break ; } a [ i ] -= 1 ; ctr += 1 ; i = ( i - 1 + n ) % n ; } a [ start ] = ctr ; for ( i = 0 ; i < n ; i ++ ) { document . write ( a [ i ] + " " ) ; } } let N = 5 ; let P = 2 ; let arr = [ 3 , 2 , 0 , 2 , 7 ] ; findArray ( arr , N , P ) ;