Skip to content

Instantly share code, notes, and snippets.

@uemuraj
Last active January 18, 2023 23:39
Show Gist options
  • Save uemuraj/4b3fda4f0f549b16b03eb8474c70938d to your computer and use it in GitHub Desktop.
Save uemuraj/4b3fda4f0f549b16b03eb8474c70938d to your computer and use it in GitHub Desktop.
FizzBuzz あれこれ
#include <iostream>
#if 0
int main()
{
for (int i = 1; i <= 100; ++i)
{
const int fizz = i % 3, buzz = i % 5;
if (fizz == 0)
{
std::cout << "fizz";
}
if (buzz == 0)
{
std::cout << "buzz";
}
if (fizz && buzz)
{
std::cout << i;
}
std::cout << std::endl;
}
}
#elif 0
struct fizzbuzz
{
const int value;
};
std::ostream & operator<<(std::ostream & out, const fizzbuzz & obj)
{
const int fizz = obj.value % 3, buzz = obj.value % 5;
if (fizz == 0)
{
out << "fizz";
}
if (buzz == 0)
{
out << "buzz";
}
if (fizz && buzz)
{
out << obj.value;
}
return out;
}
fizzbuzz put_fizzbuzz(int i)
{
return { i };
}
int main()
{
for (int i = 1; i <= 100; ++i)
{
std::cout << put_fizzbuzz(i) << std::endl;
}
}
#elif 0
class put_fizzbuzz
{
const int value;
friend std::ostream & operator<<(std::ostream & out, const put_fizzbuzz & obj)
{
const int fizz = obj.value % 3, buzz = obj.value % 5;
if (fizz == 0)
{
out << "fizz";
}
if (buzz == 0)
{
out << "buzz";
}
if (fizz && buzz)
{
out << obj.value;
}
return out;
}
public:
put_fizzbuzz(int i) : value(i)
{}
};
int main()
{
for (int i = 1; i <= 100; ++i)
{
std::cout << put_fizzbuzz(i) << std::endl;
}
}
#else
#include <variant>
#include <ranges>
using fizzbuzz = std::variant<const char *, int>;
fizzbuzz put_fizzbuzz(int i)
{
const int fizz = i % 3, buzz = i % 5;
if (fizz == 0 && buzz == 0)
{
return "fizzbuzz";
}
if (fizz == 0)
{
return "fizz";
}
if (buzz == 0)
{
return "buzz";
}
return i;
}
std::ostream & operator<<(std::ostream & out, const fizzbuzz & obj)
{
if (auto p = std::get_if<const char *>(&obj); p != nullptr)
{
return out << *p;
}
return out << std::get<int>(obj);
}
int main()
{
for (int i : std::ranges::views::iota(1, 100 + 1))
{
std::cout << put_fizzbuzz(i) << std::endl;
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment