Skip to main content
1 of 3

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.

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.