Skip to content

Instantly share code, notes, and snippets.

@max-dark
Last active January 23, 2020 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save max-dark/b532278863e78809fbfb538b7e1b0d7b to your computer and use it in GitHub Desktop.
Save max-dark/b532278863e78809fbfb538b7e1b0d7b to your computer and use it in GitHub Desktop.
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