Generate n | This function generates all n bit Gray codes and prints the generated codes ; base case ; ' arr ' will store all generated codes ; start with one - bit pattern ; Every iteration of this loop generates 2 * i codes from previously generated i codes . ; Enter the prviously generated codes again in arr [ ] in reverse order . Nor arr [ ] has double number of codes . ; append 0 to the first half ; append 1 to the second half ; print contents of arr [ ] ; Driver program to test above function
function generateGrayarr ( n ) { if ( n <= 0 ) return ; let arr = [ ] ; arr . push ( " " ) ; arr . push ( " " ) ; let i , j ; for ( i = 2 ; i < ( 1 << n ) ; i = i << 1 ) { for ( j = i - 1 ; j >= 0 ; j -- ) arr . push ( arr [ j ] ) ; for ( j = 0 ; j < i ; j ++ ) arr [ j ] = " " + arr [ j ] ; for ( j = i ; j < 2 * i ; j ++ ) arr [ j ] = " " + arr [ j ] ; } for ( i = 0 ; i < arr . length ; i ++ ) document . write ( arr [ i ] + " " ) ; } generateGrayarr ( 3 ) ;