Binary string with given frequencies of sums of consecutive pairs of characters | A Function that generates and returns the binary string ; P : Frequency of consecutive characters with sum 0 Q : Frequency of consecutive characters with sum 1 R : Frequency of consecutive characters with sum 2 ; If no consecutive character adds up to 1 ; Not possible if both P and Q are non - zero ; If P is not equal to 0 ; Append 0 P + 1 times ; Append 1 R + 1 times ; Append "01" to satisfy Q ; Append "0" P times ; Append "1" R times ; Driver Code
function build_binary_str ( p , q , r ) { let ans = " " ; if ( q == 0 ) { if ( p != 0 && r != 0 ) { return " " ; } else { if ( p ) { ans = new Array ( p + 1 , ' ' ) ; } else { ans = String ( r + 1 , ' ' ) ; } } } else { for ( let i = 1 ; i <= q + 1 ; i ++ ) { if ( i % 2 == 0 ) { ans += ' ' ; } else { ans += ' ' ; } } ans = ans . substr ( 0 , 1 ) + Strings ( p , ' ' ) + ans . substr ( 1 ) ; ans = Strings ( r , ' ' ) + ans ; } return ans ; } function Strings ( p , c ) { let ans = " " ; for ( let i = 0 ; i < p ; i ++ ) ans += c ; return ans ; } let p = 1 , q = 2 , r = 2 ; document . write ( build_binary_str ( p , q , r ) ) ;