Generate n | This function generates all n bit Gray codes and prints the generated codes ; Base case ; Recursive case ; Append 0 to the first half ; Append 1 to the second half ; Function to generate the Gray code of N bits ; print contents of arr ; Driver Code
function generateGray ( n ) { if ( n <= 0 ) { let temp = [ " " ] ; return temp ; } if ( n == 1 ) { let temp = [ " " , " " ] ; return temp ; } let recAns = generateGray ( n - 1 ) ; let mainAns = [ ] ; for ( let i = 0 ; i < recAns . length ; i ++ ) { let s = recAns [ i ] ; mainAns . push ( " " + s ) ; } for ( let i = recAns . length - 1 ; i >= 0 ; i -- ) { let s = recAns [ i ] ; mainAns . push ( " " + s ) ; } return mainAns ; } function generateGrayarr ( n ) { let arr = [ ] ; arr = generateGray ( n ) ; for ( let i = 0 ; i < arr . length ; i ++ ) { document . write ( arr [ i ] + " " ) ; } } generateGrayarr ( 3 ) ;