# Posted By

dirkchang on 03/28/11

# Statistics

Viewed 306 times
Favorited by 0 user(s)

# 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);}`