nchoosek.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2015 Olga Diamanti, Alec Jacobson
  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 "nchoosek.h"
  9. #include <cmath>
  10. #include <cassert>
  11. IGL_INLINE double igl::nchoosek(const int n, const int k)
  12. {
  13. if(k>n/2)
  14. {
  15. return nchoosek(n,n-k);
  16. }else if(k==1)
  17. {
  18. return n;
  19. }else
  20. {
  21. double c = 1;
  22. for(int i = 1;i<=k;i++)
  23. {
  24. c *= (((double)n-k+i)/((double)i));
  25. }
  26. return std::round(c);
  27. }
  28. }
  29. template < typename DerivedV, typename DerivedU>
  30. IGL_INLINE void igl::nchoosek(
  31. const Eigen::MatrixBase<DerivedV> & V,
  32. const int k,
  33. Eigen::PlainObjectBase<DerivedU> & U)
  34. {
  35. using namespace Eigen;
  36. if(V.size() == 0)
  37. {
  38. U.resize(0,k);
  39. return;
  40. }
  41. assert((V.cols() == 1 || V.rows() == 1) && "V must be a vector");
  42. U.resize(nchoosek(V.size(),k),k);
  43. int running_i = 0;
  44. int running_j = 0;
  45. Matrix<typename DerivedU::Scalar,1,Dynamic> running(1,k);
  46. int N = V.size();
  47. const std::function<void(int,int)> doCombs =
  48. [&running,&N,&doCombs,&running_i,&running_j,&U,&V](int offset, int k)
  49. {
  50. if(k==0)
  51. {
  52. U.row(running_i) = running;
  53. running_i++;
  54. return;
  55. }
  56. for (int i = offset; i <= N - k; ++i)
  57. {
  58. running(running_j) = V(i);
  59. running_j++;
  60. doCombs(i+1,k-1);
  61. running_j--;
  62. }
  63. };
  64. doCombs(0,k);
  65. }
  66. #ifdef IGL_STATIC_LIBRARY
  67. // Explicit template specialization
  68. template void igl::nchoosek<Eigen::CwiseNullaryOp<Eigen::internal::linspaced_op<int, true>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::MatrixBase<Eigen::CwiseNullaryOp<Eigen::internal::linspaced_op<int, true>, Eigen::Matrix<int, -1, 1, 0, -1, 1> > > const&, int, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&);
  69. template void igl::nchoosek<Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::MatrixBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > const&, int, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&);
  70. #endif