Count Derangements ( Permutation such that no element appears in its original position ) | Function to count derangements ; Base cases ; countDer ( n ) = ( n - 1 ) [ countDer ( n - 1 ) + der ( n - 2 ) ] ; Driver Code
function countDer ( n ) { if ( n == 1 ) return 0 ; if ( n == 2 ) return 1 ; return ( n - 1 ) * ( countDer ( n - 1 ) + countDer ( n - 2 ) ) ; } let n = 4 ; document . write ( " " + countDer ( n ) ) ;