Sprout/example/fizzbuzz/main.cpp

82 lines
1.7 KiB
C++
Raw Normal View History

2012-05-22 12:16:16 +00:00
//
// Sprout C++ Library
//
// Copyright (c) 2012
// bolero-MURAKAMI : http://d.hatena.ne.jp/boleros/
// osyo-manga : http://d.hatena.ne.jp/osyo-manga/
//
// Readme:
// https://github.com/bolero-MURAKAMI/Sprout/blob/master/README
//
// License:
// Boost Software License - Version 1.0
// <http://www.boost.org/LICENSE_1_0.txt>
//
#include <sprout/string.hpp>
struct fizzbuzz{
typedef sprout::string<12> result_type;
constexpr result_type
2014-02-19 23:04:36 +00:00
operator()(int n) const {
2014-02-19 23:12:02 +00:00
return n % 15 == 0 ? "FizzBuzz"
: n % 3 == 0 ? "Fizz"
: n % 5 == 0 ? "Buzz"
2012-05-22 12:16:16 +00:00
: sprout::to_string(n);
}
};
2014-02-19 23:12:02 +00:00
//
// Test
//
static_assert(fizzbuzz()( 1) == "1", "");
static_assert(fizzbuzz()( 2) == "2", "");
static_assert(fizzbuzz()( 3) == "Fizz", "");
static_assert(fizzbuzz()( 5) == "Buzz", "");
static_assert(fizzbuzz()(15) == "FizzBuzz", "");
#include <sprout/array.hpp>
#include <sprout/algorithm/transform.hpp>
#include <sprout/numeric/iota.hpp>
#include <iostream>
2012-05-22 12:16:16 +00:00
int
main(){
typedef fizzbuzz::result_type string;
//
// Sequence [1..15]
//
2014-02-19 23:04:36 +00:00
constexpr auto source = sprout::iota<sprout::array<int, 15> >(1);
2012-05-22 12:16:16 +00:00
//
// Transform to FizzBuzz
//
2014-02-19 23:04:36 +00:00
constexpr auto result = sprout::transform<sprout::array<string, 15> >(
2012-05-22 12:16:16 +00:00
sprout::begin(source),
sprout::end(source),
fizzbuzz()
2014-02-19 23:04:36 +00:00
);
2012-05-22 12:16:16 +00:00
//
// Check result
//
constexpr auto fizzbuzz_result = sprout::make_array<string>(
2014-02-19 23:12:02 +00:00
"1", "2", "Fizz", "4", "Buzz",
"Fizz", "7", "8", "Fizz", "Buzz",
"11", "Fizz", "13", "14", "FizzBuzz"
2014-02-19 23:04:36 +00:00
);
2012-05-22 12:16:16 +00:00
// Equal result sequence
static_assert(result == fizzbuzz_result, "");
//
// Output
//
2014-02-19 23:12:02 +00:00
for (auto&& str : result) {
2012-05-22 12:16:16 +00:00
std::cout << str << ", ";
}
std::cout << std::endl;
}