Generate all binary strings of length n with sub | Utility function to print the given binary string ; This function will be called recursively to generate the next bit for given binary string according to its current state ; Base - case : if the generated binary string meets the required length and the pattern "01" appears twice ; nextbit needs to be 0 because each time we call the function recursively , we call 2 times for 2 cases : next bit is 0 or 1 The is to assure that the binary string is printed one time only ; Generate the next bit for str and call recursive ; Assign first bit ; The next generated bit will wither be 0 or 1 ; If pattern "01" occurrence is < 2 ; Set next bit ; If pattern "01" appears then increase the occurrence of pattern ; Else pattern "01" occurrence equals 2 ; If previous bit is 0 then next bit cannot be 1 ; Otherwise ; Driver code ; Length of the resulting strings must be at least 4 ; Generate all binary strings of length n with sub - string "01" appearing twice
function printBinStr ( str , len ) { for ( var i = 0 ; i < len ; i ++ ) { document . write ( str [ i ] ) ; } document . write ( " " ) ; } function generateBinStr ( str , len , currlen , occur , nextbit ) { if ( currlen == len ) { if ( occur == 2 && nextbit == 0 ) printBinStr ( str , len ) ; return ; } if ( currlen == 0 ) { str [ 0 ] = nextbit ; generateBinStr ( str , len , currlen + 1 , occur , 0 ) ; generateBinStr ( str , len , currlen + 1 , occur , 1 ) ; } else { if ( occur < 2 ) { str [ currlen ] = nextbit ; if ( str [ currlen - 1 ] == 0 && nextbit == 1 ) { occur += 1 ; } generateBinStr ( str , len , currlen + 1 , occur , 0 ) ; generateBinStr ( str , len , currlen + 1 , occur , 1 ) ; } else { if ( str [ currlen - 1 ] == 0 && nextbit == 1 ) { return ; } else { str [ currlen ] = nextbit ; generateBinStr ( str , len , currlen + 1 , occur , 0 ) ; generateBinStr ( str , len , currlen + 1 , occur , 1 ) ; } } } } var n = 5 ; if ( n < 4 ) document . write ( - 1 ) ; else { var str = Array ( n ) ; generateBinStr ( str , n , 0 , 0 , 0 ) ; generateBinStr ( str , n , 0 , 0 , 1 ) ; }