Count number of ways to arrange first N numbers | Function to return the count of required arrangements ; Create a vector ; Store numbers from 1 to n ; To store the count of ways ; Generate all the permutations using next_permutation in STL ; Initialize flag to true if first element is 1 else false ; Checking if the current permutation satisfies the given conditions ; If the current permutation is invalid then set the flag to false ; If valid arrangement ; Generate the next permutation ;  ; Driver code
function countWays ( n ) { let a = [ ] ; let i = 1 ; while ( i <= n ) a . push ( i ++ ) ; let ways = 0 ; do { let flag = ( a [ 0 ] == 1 ) ; for ( let j = 1 ; j < n ; j ++ ) { if ( Math . abs ( a [ j ] - a [ j - 1 ] ) > 2 ) flag = false ; } if ( flag ) ways ++ ; } while ( next_permutation ( a ) ) ; return ways ; } function next_permutation ( p ) { for ( let a = p . length - 2 ; a >= 0 ; -- a ) { if ( p [ a ] < p [ a + 1 ] ) { for ( let b = p . length - 1 ; ; -- b ) { if ( p [ b ] > p [ a ] ) { let t = p [ a ] ; p [ a ] = p [ b ] ; p [ b ] = t ; for ( ++ a , b = p . length - 1 ; a < b ; ++ a , -- b ) { t = p [ a ] ; p [ a ] = p [ b ] ; p [ b ] = t ; } return true ; } } } } return false ; } let n = 6 ; document . write ( countWays ( n ) ) ;