The below is the C# implementation for the a function for given parameters int a
, int b
- both represent characters 'A' and 'B' respectively, where the function should return a string containing both characters 'A' and 'B' occurring a
times and b
times respectively but neither 'A' nor 'B' repeating consecutively for more than 2 times.
eg:
Foo(3,3)
returns "BBAABA
" or "AABBAB
"
Foo(4,1)
returns "AABAA
"
Foo(3,5)
returns "BAABBABB
" or "BBAABBAB
"
Code:
string Foo(int a, int b)
{
int total = a + b;
StringBuilder sb = new StringBuilder();
char charToPrint = a > b ? 'A' : 'B';
int flag = 0;
for(int x =0; x< total; x++)
{
if(flag == 2)
{
flag = 0;
charToPrint = SwapChar(charToPrint);
}
if(charToPrint == 'A' && a == 0 || charToPrint == 'B' && b == 0)
{
charToPrint = SwapChar(charToPrint);
}
if (charToPrint == 'A')
a--;
else
b--;
sb.Append(charToPrint);
flag++;
}
return sb.ToString();
}
This is working but I would like to receive some feedback on this code.