## Posted By

dirkchang on 03/28/11

# Combination (no pointer, only array)

/ Published in: C++

`/* * combination.cpp * *  Created on: 2011/3/25 *      Author: dirk */// for convenience, indexing in this alg. starts from 1 #include <iostream>using namespace std; #define MAX 512 inline int advance_and_relax(int digits[], int m, int n) {    if(n == 1) return 0; // no way to advance    for(int i = n - 1; i >= 1; --i) {        if(++digits[i] <= (m - n + i)) { // digits[i] is able to advance            for(int cur_index = i+1, cur_value = digits[i]+1; cur_index <= n; ++cur_index) { // we relax all digits behind digits[i]                digits[cur_index] = cur_value++;            }               return 1;        }       }       return 0;} inline void C(int x[], int m, int n) {    int digits[MAX+1]; // our indexing starts from 1    for(int i = 0; i < n + 1; ++i) digits[i] = i; // initialization    int finish = 0;    while(finish == 0) {        for(int i = 1; i <= n; ++i) cout << x[digits[i]] << ' ';        cout << '\n';        if(++digits[n] > m) {            if(advance_and_relax(digits, m, n) == 1) finish = 0;            else finish = 1;        }       }   } int main() {    int m, n;    int x[MAX+1];    cout << "M = ? ";    cin >> m;    cout << "N = ? ";    cin >> n;    cout << "輸入 M 個數字: ";    for(int i = 1; i <= m; ++i) cin >> x[i];    if(m < n || m <=0 || n <= 0 || m > 512) {        cout << "輸入格式不正確, 界線條件是 M > N 且 M, N > 0\n"             << "記憶體限制是 M 必須小於等於 512\n"             << "真的 M 太大也會算很久怕你沒耐心XD\n";        return -1;    }    C(x, m, n);}`