Count number of ways to arrange first N numbers | C # implementation of the above approach ; 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
using System ; using System . Collections . Generic ; class GFG { static int countWays ( int n ) { List < int > a = new List < int > ( ) ; int i = 1 ; while ( i <= n ) a . Add ( i ++ ) ; int ways = 0 ; do { bool flag = ( a [ 0 ] == 1 ) ; for ( int 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 ; } static bool next_permutation ( List < int > p ) { for ( int a = p . Count - 2 ; a >= 0 ; -- a ) if ( p [ a ] < p [ a + 1 ] ) for ( int b = p . Count - 1 ; ; -- b ) if ( p [ b ] > p [ a ] ) { int t = p [ a ] ; p [ a ] = p [ b ] ; p [ b ] = t ; for ( ++ a , b = p . Count - 1 ; a < b ; ++ a , -- b ) { t = p [ a ] ; p [ a ] = p [ b ] ; p [ b ] = t ; } return true ; } return false ; } public static void Main ( String [ ] args ) { int n = 6 ; Console . Write ( countWays ( n ) ) ; } }