From 4d70a437ce4d9b17d717dfe1de1d7282fd853ee8 Mon Sep 17 00:00:00 2001 From: bolero-MURAKAMI Date: Sun, 4 Aug 2013 00:05:39 +0900 Subject: [PATCH] add example: inv_fizzbuzz --- example/inv_fizzbuzz/main.cpp | 89 +++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 example/inv_fizzbuzz/main.cpp diff --git a/example/inv_fizzbuzz/main.cpp b/example/inv_fizzbuzz/main.cpp new file mode 100644 index 00000000..8e4632be --- /dev/null +++ b/example/inv_fizzbuzz/main.cpp @@ -0,0 +1,89 @@ + +#include +#include +#include +#include +#include +#include +#include + +static constexpr auto token_table = sprout::to_string_array >( + "Fizz", "Buzz", "Fizz", "Fizz", "Buzz", "Fizz", "FizzBuzz", + "Fizz", "Buzz", "Fizz", "Fizz", "Buzz", "Fizz" + ); +static constexpr auto index_table = sprout::make_array( + 3, 5, 6, 9, 10, 12, 15, + 18, 20, 21, 24, 25, 27 + ); + +template +constexpr sprout::pair +inv_fizzbuzz_impl(ForwardRange const& rng, Difference found) { + return found == sprout::size(token_table) ? sprout::pair{0, 0} + : sprout::pair{ + index_table[found], + sprout::size(rng) / 7 * 15 + index_table[found + sprout::size(rng) % 7 - 1] + } + ; +} +template +constexpr sprout::pair +inv_fizzbuzz(ForwardRange const& rng) { + return sprout::size(rng) <= 7 + || (sprout::size(sprout::range::find_end(rng, rng | sprout::adaptors::taken(7))) == 7 + sprout::size(rng) % 7 + && sprout::range::equal( + rng | sprout::adaptors::taken(sprout::size(rng) % 7), + rng | sprout::adaptors::dropped(sprout::size(rng) - sprout::size(rng) % 7) + ) + ) + ? inv_fizzbuzz_impl( + rng, + sprout::size(sprout::range::search(token_table, rng | sprout::adaptors::taken(7))) + ) + : sprout::pair{0, 0} + ; +} + +#include + +template +void print(ForwardRange const& input, Pair const& answer) { + std::cout << "input : "; + for (auto const& e : input) { + std::cout << e << ' '; + } + std::cout << std::endl; + std::cout << "answer: (" << answer.first << ',' << answer.second << ')' << std::endl; +} + +int main() { + { + constexpr auto input = sprout::to_string_array >( + "Fizz", "FizzBuzz", "Fizz", "Buzz" + ); + constexpr auto answer = inv_fizzbuzz(input); + + static_assert(answer.first == 12 && answer.second == 20, "answer is (12,20)"); + print(input, answer); + } + { + constexpr auto input = sprout::to_string_array >( + "FizzBuzz", "Fizz", "Buzz", "Fizz", "Fizz", "Buzz", "Fizz", + "FizzBuzz", "Fizz", "Buzz", "Fizz", "Fizz", "Buzz", "Fizz", + "FizzBuzz", "Fizz", "Buzz" + ); + constexpr auto answer = inv_fizzbuzz(input); + + static_assert(answer.first == 15 && answer.second == 50, "answer is (15,50)"); + print(input, answer); + } + { + constexpr auto input = sprout::to_string_array >( + "Fizz", "FizzBuzz", "Buzz" + ); + constexpr auto answer = inv_fizzbuzz(input); + + static_assert(answer.first == 0 && answer.second == 0, "answer is (0,0)"); + print(input, answer); + } +}