permutations.hpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*!
  2. @file
  3. Defines `boost::hana::permutations`.
  4. Copyright Louis Dionne 2013-2022
  5. Distributed under the Boost Software License, Version 1.0.
  6. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
  7. */
  8. #ifndef BOOST_HANA_PERMUTATIONS_HPP
  9. #define BOOST_HANA_PERMUTATIONS_HPP
  10. #include <boost/hana/fwd/permutations.hpp>
  11. #include <boost/hana/at.hpp>
  12. #include <boost/hana/concept/sequence.hpp>
  13. #include <boost/hana/config.hpp>
  14. #include <boost/hana/core/dispatch.hpp>
  15. #include <boost/hana/core/make.hpp>
  16. #include <boost/hana/detail/array.hpp>
  17. #include <boost/hana/length.hpp>
  18. #include <cstddef>
  19. #include <utility>
  20. namespace boost { namespace hana {
  21. //! @cond
  22. template <typename Xs>
  23. constexpr auto permutations_t::operator()(Xs&& xs) const {
  24. using S = typename hana::tag_of<Xs>::type;
  25. using Permutations = BOOST_HANA_DISPATCH_IF(permutations_impl<S>,
  26. hana::Sequence<S>::value
  27. );
  28. #ifndef BOOST_HANA_CONFIG_DISABLE_CONCEPT_CHECKS
  29. static_assert(hana::Sequence<S>::value,
  30. "hana::permutations(xs) requires 'xs' to be a Sequence");
  31. #endif
  32. return Permutations::apply(static_cast<Xs&&>(xs));
  33. }
  34. //! @endcond
  35. namespace detail {
  36. template <std::size_t N>
  37. struct permutation_indices {
  38. static constexpr auto value =
  39. detail::array<std::size_t, N>{}.iota(0).permutations();
  40. };
  41. }
  42. template <typename S, bool condition>
  43. struct permutations_impl<S, when<condition>> : default_ {
  44. template <std::size_t n, typename Xs, std::size_t ...i>
  45. static constexpr auto
  46. nth_permutation(Xs const& xs, std::index_sequence<i...>) {
  47. constexpr auto indices = detail::permutation_indices<sizeof...(i)>::value;
  48. (void)indices; // workaround GCC warning when sizeof...(i) == 0
  49. return hana::make<S>(hana::at_c<indices[n][i]>(xs)...);
  50. }
  51. template <std::size_t N, typename Xs, std::size_t ...n>
  52. static constexpr auto
  53. permutations_helper(Xs const& xs, std::index_sequence<n...>) {
  54. return hana::make<S>(nth_permutation<n>(xs, std::make_index_sequence<N>{})...);
  55. }
  56. template <typename Xs>
  57. static constexpr auto apply(Xs const& xs) {
  58. constexpr std::size_t N = decltype(hana::length(xs))::value;
  59. constexpr std::size_t total_perms = detail::factorial(N);
  60. return permutations_helper<N>(xs, std::make_index_sequence<total_perms>{});
  61. }
  62. };
  63. }} // end namespace boost::hana
  64. #endif // !BOOST_HANA_PERMUTATIONS_HPP