Smallest Derangement of Sequence | Javascript program to find smallest derangement . ; Generate Sequence S ; Generate Derangement ; Only if i is odd Swap S [ N - 1 ] and S [ N ] ; Prlet Derangement ; Driver code
function generate_derangement ( N ) { let S = [ ] ; for ( let i = 1 ; i <= N ; i ++ ) S [ i ] = i ; let D = [ ] ; for ( let i = 1 ; i <= N ; i += 2 ) { if ( i == N ) { D [ N ] = S [ N - 1 ] ; D [ N - 1 ] = S [ N ] ; } else { D [ i ] = i + 1 ; D [ i + 1 ] = i ; } } for ( let i = 1 ; i <= N ; i ++ ) document . write ( D [ i ] + " " ) ; document . write ( " " ) ; } generate_derangement ( 10 ) ;