randperm.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public License
  6. // v. 2.0. If a copy of the MPL was not distributed with this file, You can
  7. // obtain one at http://mozilla.org/MPL/2.0/.
  8. #include "randperm.h"
  9. #include "colon.h"
  10. #include <algorithm>
  11. template <typename DerivedI>
  12. IGL_INLINE void igl::randperm(
  13. const int n,
  14. Eigen::PlainObjectBase<DerivedI> & I,
  15. const int64_t rng_min,
  16. const int64_t rng_max,
  17. const std::function<int64_t()> &rng)
  18. {
  19. Eigen::VectorXi II;
  20. igl::colon(0,1,n-1,II);
  21. I = II;
  22. // C++ named requirement : UniformRandomBitGenerator
  23. // This signature is required for the third parameter of
  24. // std::shuffle
  25. struct RandPermURBG {
  26. public:
  27. using result_type = int64_t;
  28. RandPermURBG(const result_type min,
  29. const result_type max,
  30. const std::function<result_type()> int_gen) :
  31. m_min(min),
  32. m_max(max),
  33. m_int_gen(std::move(int_gen)) {}
  34. result_type min() const noexcept { return m_min; }
  35. result_type max() const noexcept { return m_max; }
  36. result_type operator()() const { return m_int_gen(); };
  37. private:
  38. result_type m_min;
  39. result_type m_max;
  40. std::function<result_type()> m_int_gen;
  41. };
  42. const auto int_gen = (nullptr != rng) ?
  43. rng :
  44. []()->int64_t { return std::rand(); };
  45. std::shuffle(I.data(),I.data()+n, RandPermURBG(rng_min, rng_max, int_gen));
  46. }
  47. #ifdef IGL_STATIC_LIBRARY
  48. // Explicit template instantiation
  49. template void igl::randperm<Eigen::Matrix<int, -1, 1, 0, -1, 1> >(int, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, const int64_t, const int64_t, const std::function<int64_t()>&);
  50. template void igl::randperm<Eigen::Matrix<int, -1, -1, 0, -1, -1> >(int, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, const int64_t, const int64_t, const std::function<int64_t()>&);
  51. #endif