Count of pass required to visit same index again by moving arr [ i ] to index arr [ i ] | Java program for the above approach ; Function to find the number of moves required to visit the same index again for every array element ; Make given array 0 index based ; Stores the number of moves ; Store index value ; Update the value of cnt ; Make a pass ; Print the value of cnt ; Driver Code
import java . io . * ; class GFG { static void numberOfPasses ( int [ ] arr , int N ) { for ( int i = 0 ; i < N ; ++ i ) { -- arr [ i ] ; } for ( int i = 0 ; i < N ; ++ i ) { int cnt = 0 ; int k = i ; do { ++ cnt ; k = arr [ k ] ; } while ( k != i ) ; System . out . print ( cnt + " ▁ " ) ; } } public static void main ( String [ ] args ) { int [ ] arr = { 4 , 6 , 2 , 1 , 5 , 3 } ; int N = arr . length ; numberOfPasses ( arr , N ) ; } }