Advertisement
alaestor

static constexpr fibbonachi vector

Dec 2nd, 2024 (edited)
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.58 KB | Source Code | 0 0
  1. /*
  2.     Playing around with flattening dynamic memory for static storage.
  3.  
  4.     Requires executing twice: once for size and once for values.
  5.     Therefor it also requires that the operation be deterministic
  6.     and consistent between executions. (No way to avoid this atm?...)
  7. */
  8.  
  9. #include <ranges> // range_value_t
  10. #include <type_traits> // invoke_result_t
  11. #include <array>
  12.  
  13. // omitting `require` clauses and concepts for brevity...
  14.  
  15. template <typename T>
  16. using typer = std::ranges::range_value_t<std::invoke_result_t<T>>;
  17.  
  18. template <typename T>
  19. constexpr std::size_t sizer{ std::ranges::size(T{}()) };
  20.  
  21. template <typename T>
  22. consteval auto crystallizer()
  23. {
  24.     std::array<typer<T>, sizer<T>> out{};
  25.     auto&& temp{ T{}() };
  26.     std::copy(temp.begin(), temp.end(), out.begin());
  27.     return out;
  28. }
  29.  
  30. #define CRYSTALLIZE(...) crystallizer<decltype([]{ return __VA_ARGS__; })>()
  31.  
  32. // arbitrary constexpr work ( this is enterprise :P gotta over-complicate it )
  33.  
  34. #include <functional> // plus
  35. #include <algorithm> // fold_left
  36. #include <ranges> // reverse_view, take
  37. #include <vector>
  38.  
  39. constexpr std::vector<int> fibby(std::size_t n)
  40. {
  41.     using namespace std::ranges;
  42.     using namespace std::ranges::views;
  43.  
  44.     if (n == 0) return std::vector<int>{};
  45.     if (n == 1) return std::vector<int>({0});
  46.  
  47.     std::vector<int> seq({0,1});
  48.     for (std::size_t i{ 2 }; i < n; ++i)
  49.         seq.push_back(fold_left(reverse_view(seq) | take(2), 0, std::plus<int>()));
  50.  
  51.     return seq;
  52. }
  53.  
  54. // demo
  55.  
  56. #include <iostream>
  57.  
  58. int main()
  59. {
  60.     for (auto& e : CRYSTALLIZE(fibby(20)))
  61.         std::cout << e << ", ";
  62. }
  63.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement