Minimum array elements to be changed to make Recaman 's sequence | Javascript implementation of the approach ; First term of the sequence is always 0 ; Fill remaining terms using recursive formula ; If arr [ i - 1 ] - i is negative or already exists ; Function that returns minimum changes required ; Set to store first n Recaman numbers ; Generate and store first n Recaman numbers ; push first n Recaman numbers to set ; If current element of the array is present in the set ; Return the remaining number of elements in the set ; Driver code
function recamanGenerator ( arr , n ) { arr [ 0 ] = 0 ; for ( var i = 1 ; i <= n ; i ++ ) { var temp = arr [ i - 1 ] - i ; var j ; for ( j = 0 ; j < i ; j ++ ) { if ( ( arr [ j ] == temp ) temp < 0 ) { temp = arr [ i - 1 ] + i ; break ; } } arr [ i ] = temp ; } } function recamanArray ( arr , n ) { var s = [ ] ; var recaman = Array ( n ) . fill ( 0 ) ; recamanGenerator ( recaman , n ) ; for ( var i = 0 ; i < n ; i ++ ) s . push ( recaman [ i ] ) ; s . sort ( ( a , b ) => b - a ) for ( var i = 0 ; i < n ; i ++ ) { if ( s . includes ( arr [ i ] ) ) { s . splice ( s . indexOf ( arr [ i ] ) , 1 ) ; } } return s . length ; } var arr = [ 7 , 11 , 20 , 4 , 2 , 1 , 8 , 6 ] ; var n = arr . length ; document . write ( recamanArray ( arr , n ) ) ;