Binary string with given frequencies of sums of consecutive pairs of characters | C ++ program to generate a binary string with given frequencies of sums of consecutive pair 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; string build_binary_str ( int p , int q , int r ) { string ans = " " ; if ( q == 0 ) { if ( p != 0 && r != 0 ) { return " - 1" ; } else { if ( p ) { ans = string ( p + 1 , '0' ) ; } else { ans = string ( r + 1 , '1' ) ; } } } else { for ( int i = 1 ; i <= q + 1 ; i ++ ) { if ( i % 2 == 0 ) { ans += '0' ; } else { ans += '1' ; } } ans . insert ( 1 , string ( p , '0' ) ) ; ans . insert ( 0 , string ( r , '1' ) ) ; } return ans ; } int main ( ) { int p = 1 , q = 2 , r = 2 ; cout << build_binary_str ( p , q , r ) ; return 0 ; }