Generate an array of size N according to the given rules | Function to search the most recent location of element N If not present in the array it will return - 1 ; Function to generate an array of size N by following the given rules ; Loop to fill the array as per the given rules ; Check for the occurrence of arr [ i - 1 ] ; Driver code
function search ( a , k , x ) { var j ; for ( j = k - 1 ; j > - 1 ; j -- ) { if ( a [ j ] == x ) return j ; } return - 1 ; } function genArray ( arr , N ) { for ( var i = 0 ; i < N - 1 ; i ++ ) { if ( search ( arr , i , arr [ i ] ) == - 1 ) arr [ i + 1 ] = 0 ; else arr [ i + 1 ] = ( i - search ( arr , i , arr [ i ] ) ) ; } } var N = 5 ; var size = N + 1 ; var a = [ 0 , 0 , 0 , 0 , 0 ] ; genArray ( a , N ) ; document . write ( " " + a + " " ) ;