DEV Community

Discussion on: [Challenge] 🐝 FizzBuzz without if/else

Collapse
jselbie profile image
John Selbie • Edited on

Trick is to map the modulo results into a true/false value. Then use that as a 0 or 1 index into an array of two strings.

C++

void fizzbuzz(int N)
{
    const string fizzstrings[2] = { "Fizz", "" };
    const string buzzstrings[2] = { "Buzz", "" };

    for (int i = 1; i <= N; i++)
    {
        int fizz = !!(i % 3);   // 0 if i is divisible by 3, 1 otherwise
        int buzz = !!(i % 5);   // 0 if i is divisible by 5, 1 otherwise
        int use_number = fizz && buzz;    // 1 if is neither divisible by 3 or 5, 0 otherwise
        string table[2] = { "", to_string(i) };
        cout << fizzstrings[fizz] << buzzstrings[buzz] << table[use_number] << endl;
    }
}

And the above can be further reduced to a single array table by exploiting multiplication against a bool expression

void fizzbuzz(int N)
{
    for (int i = 1; i <= N; i++)
    {
        const string fb[4] = { "", "Fizz", "Buzz", to_string(i) };
        int fizz = !(i % 3);                   // 0 or 1
        int buzz = (!(i % 5)) * 2;             // 0 or 2
        int numIndex = (!fizz && !buzz) * 3;   // 0 or 3
        cout << fb[fizz] << fb[buzz] << fb[numIndex] << endl;
    }
}