Building a string with only two repeating characters 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. Both values for a and b are given in a way that a string can be build using those numbers - so eg: Foo(0,3) or Foo(1,7) shall not be invoked.
eg:
Foo(3,3) returns &quot;BBAABA&quot; or &quot;AABBAB&quot;
Foo(4,1) returns &quot;AABAA&quot;
Foo(3,5) returns &quot;BAABBABB&quot; or &quot;BBAABBAB&quot;
Code:
static string Foo(int a, int b)
{
    int total = a + b;
    StringBuilder sb = new StringBuilder();
    char charToPrint = a &gt; b ? 'A' : 'B';
    int flag = 0;

    for(int x =0; x&lt; total; x++)
    {
        if(flag == 2)
        {
            flag = 0;
            charToPrint = SwapChar(charToPrint);
        }
        if(charToPrint == 'A' &amp;&amp; a == 0 || charToPrint == 'B' &amp;&amp; b == 0)
        {
            charToPrint = SwapChar(charToPrint);
        }

        if (charToPrint == 'A')
            a--;
        else
            b--;

        sb.Append(charToPrint);
        flag++;
    }
    return sb.ToString();
}

static char SwapChar(char thisChar)
{
    return thisChar == 'A' ? 'B' : 'A';
}

This is working but I would like to receive some feedback on this code.
Your algorithm has a flaw - it's too greedy. Take this example:
Foo(6, 2) // &quot;AABBAAAA&quot;

Alas, it should return &quot;AABAABAA&quot;.
In terms of a review, your method shouldn't be called Foo - give it a descriptive name.
Great use of StringBuilder. You could initialize the length to a+b in the constructor as you know what size your finished string will be.
Expression bodied members can greatly improve readability in my opinion:
static char SwapChar(char c) =&gt; 
    c == 'A' ? 'B' : 'A';

Try to avoid variables like flag. I had to read the whole loop before I knew what that variable meant. I'd call it something like repeatCount.