Count number of ways to arrange first N numbers | Java 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
import java . util . * ; class GFG { static int countWays ( int n ) { Vector < Integer > a = new Vector < > ( ) ; int i = 1 ; while ( i <= n ) a . add ( i ++ ) ; int ways = 0 ; do { boolean flag = ( a . get ( 0 ) == 1 ) ; for ( int j = 1 ; j < n ; j ++ ) { if ( Math . abs ( a . get ( j ) - a . get ( j - 1 ) ) > 2 ) flag = false ; } if ( flag ) ways ++ ; } while ( next_permutation ( a ) ) ; return ways ; } static boolean next_permutation ( Vector < Integer > p ) { for ( int a = p . size ( ) - 2 ; a >= 0 ; -- a ) if ( p . get ( a ) < p . get ( a + 1 ) ) for ( int b = p . size ( ) - 1 ; ; -- b ) if ( p . get ( b ) > p . get ( a ) ) { int t = p . get ( a ) ; p . set ( a , p . get ( b ) ) ; p . set ( b , t ) ; for ( ++ a , b = p . size ( ) - 1 ; a < b ; ++ a , -- b ) { t = p . get ( a ) ; p . set ( a , p . get ( b ) ) ; p . set ( b , t ) ; } return true ; } return false ; } public static void main ( String [ ] args ) { int n = 6 ; System . out . print ( countWays ( n ) ) ; } }