#include <functional> // std::function #include <memory> // std::shared_ptr #include <vector> #include <iostream> using namespace std; // n 取 r 做排列 // 採用逆時旋轉排列法 // 必須 n >= r class Permutation_nPr { // 回報結果 function<void(const shared_ptr<vector<unsigned char> > &, size_t)> m_Report; // 放置要排列的數字 shared_ptr <vector<unsigned char> > m_Digital_Array; // 要做排列的數目值 size_t m_r; void v(size_t n, size_t r) { if (r == 0) m_Report(m_Digital_Array, m_r); else v(n - 1, r - 1); for (size_t j = n; j > 0; --j) { { unsigned char tmp = m_Digital_Array->at(n); m_Digital_Array->at(n) = m_Digital_Array->at(j-1); m_Digital_Array->at(j - 1) = tmp; } if (r == 0) m_Report(m_Digital_Array, m_r); else v(n - 1, r - 1); { unsigned char tmp = m_Digital_Array->at(n); m_Digital_Array->at(n) = m_Digital_Array->at(j-1); m_Digital_Array->at(j - 1) = tmp; } } } public: Permutation_nPr( const function<void(const shared_ptr<vector<unsigned char> > &, size_t)> &Receive ):m_Report(Receive) {} void nPr(size_t n, size_t r) { m_r = r; m_Digital_Array = shared_ptr<vector<unsigned char> >(new vector<unsigned char>(n)); size_t i = n; while (i--) { m_Digital_Array->at(i) = i; } v(n - 1, r - 1); } }; class MsgShow { int N{1}; public: void ResetN(){N = 1;} void operator()( const shared_ptr<vector<unsigned char> > &Digital_Array, size_t r) { cout << N << ":\t"; for (size_t i = Digital_Array->size() - 1; r > 0; --i, --r) cout << (int)Digital_Array->at(i) << ' '; cout << endl; ++N; } }; int main() { MsgShow Report; Permutation_nPr P(Report); cout << '\n' << "4P3 排列:" << endl; Report.ResetN(); P.nPr(4,3); return 0; }
執行結果:
4P3 排列: 1: 3 2 1 2: 3 2 0 3: 3 1 2 4: 3 1 0 5: 3 0 1 6: 3 0 2 7: 2 3 1 8: 2 3 0 9: 2 1 3 10: 2 1 0 11: 2 0 1 12: 2 0 3 13: 1 2 3 14: 1 2 0 15: 1 3 2 16: 1 3 0 17: 1 0 3 18: 1 0 2 19: 0 2 1 20: 0 2 3 21: 0 1 2 22: 0 1 3 23: 0 3 1 24: 0 3 2 Process returned 0 (0x0) execution time : 0.059 s Press any key to continue.
沒有留言:
張貼留言