SHARE
TWEET

Untitled

a guest Jul 17th, 2019 83 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <array>
  2.  
  3. template <class T1, std::size_t N1, class T2, std::size_t N2>
  4. constexpr auto
  5. operator+(std::array<T1, N1> lhs, std::array<T2, N2> rhs) noexcept
  6. {
  7.     std::array<std::common_type_t<T1, T2>, N1 + N2> res = {0};
  8.  
  9.     std::size_t i = 0;
  10.     for (; i < N1 && lhs[i]; ++i)
  11.         res[i] = lhs[i];
  12.  
  13.     for (std::size_t j = 0; j < N2 && rhs[j]; ++j)
  14.         res[i + j] = rhs[j];
  15.  
  16.     return res;
  17. }
  18.  
  19. int
  20. main()
  21. {
  22.     //
  23.     // Generate FizzBuzz sequence up to 15th value
  24.     //
  25.     constexpr auto res = []<std::size_t... Is>(std::index_sequence<Is...>)
  26.     {
  27.         using Result_type = std::array<char, 10>;
  28.         auto res =
  29.           (([](auto ic) {
  30.                //
  31.                // Make a numeric representation for ic
  32.                //
  33.                std::size_t idx_last = 0;
  34.                for (std::size_t x = ic; x >= 10; x /= 10)
  35.                    ++idx_last;
  36.                Result_type num_res = {0};
  37.                for (std::size_t x = ic, i = 0; x; ++i, x /= 10)
  38.                    num_res[idx_last - i] = '0' + x % 10;
  39.  
  40.                //
  41.                // Per rules of FizzBuzz, substitute certain
  42.                // numbers with a string
  43.                //
  44.                return ic == 15
  45.                         ? Result_type{"FizzBuzz"}
  46.                         : !(ic % 3) ? Result_type{"Fizz"}
  47.                                     : !(ic % 5) ? Result_type{"Buzz"} : num_res;
  48.            }(std::integral_constant<std::size_t, Is + 1>{}) +
  49.             std::array{Is == 14 ? '\n' : ' '}) +
  50.            ...);
  51.         return res;
  52.     }
  53.     (std::make_index_sequence<15>{});
  54.  
  55.     //
  56.     // Verify correct result
  57.     //
  58.     auto is_eq_ = []<class Arr>(auto x, Arr &strlit)
  59.     {
  60.         for (std::size_t i = 0; i < std::extent_v<Arr> - 1; ++i)
  61.             if (x[i] != strlit[i])
  62.                 return false;
  63.         return true;
  64.     };
  65.     static_assert(is_eq_(res, "1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11"
  66.                               " Fizz 13 14 FizzBuzz\n"));
  67. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top