Skip to content

Instantly share code, notes, and snippets.

@max-dark
Last active Jan 23, 2020
Embed
What would you like to do?
fizz buzz without "if"
// task: https://en.wikipedia.org/wiki/Fizz_buzz
// compile: g++ -std=c++14 -Wall -Wpedantic -Werror fizz_buzz.cxx -o fizz_buzz
#include <iostream>
#include <string>
namespace
{
std::string solve(int num);
}
int main()
{
for(int num = 1; num <= 100; ++num)
{
std::cout << solve(num) << std::endl;
}
return 0;
}
namespace
{
using functor = std::string(*)(int);
std::string number(int num)
{
return std::to_string(num);
}
std::string fizz(int)
{
return "Fizz";
}
std::string buzz(int)
{
return "Buzz";
}
std::string fizz_buzz(int)
{
return "FizzBuzz";
}
functor solvers[2][2] = {
{ &number, &buzz },
{ &fizz , &fizz_buzz }
};
std::string solve(int num)
{
return (solvers[0 == num % 3][0 == num % 5])(num);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment