Permutation and Combination…again.

These here are updated versions to my previous attempts at listing permutations and combinations, and these are a lot shorter than those and easier to understand. Even though it is in C++, converting to pure C is not a huge endevour either.

Combinations

#include <iostream>
#include <string>
#include <cstdio>
#define MAX 100
using namespace std;
int count;
int r;
void comb(char *arr, int i, int j, const char *line){
    if (j<r) {
        for (int x=i;x<count;x++){
            char newline[MAX];
            sprintf(newline, "%d %s",x+1, line );
            comb(arr, x+1, j+1, newline);        
        }
    } else {
        cout<<line<<endl;
    }
}

int main(){
    cin>>count>>r;
    char bits[count];

    for (int i=0;i<count;i++) bits[i] = 0;
    comb(bits,0,0,"");
    return 0;
}

Permutations

#include <iostream>
#include <string>
#include <cstdio>
#define MAX 100
using namespace std;
int count;

void perm(char *arr, int i, const char *line){

    if (i<count) {
        for (int x=0;x<count;x++){
            if (arr[x] != 1) {
                char newline[MAX];
                sprintf(newline, "%d %s",x+1, line );

                arr[x] = 1;
                perm(arr, i+1, newline);
                arr[x] = 0;
            }
        }
    } else {
        cout<<line<<endl;
    }
}

int main(){
    cin>>count;
    char bits[count];

    for (int i=0;i<count;i++) bits[i] = 0;
    perm(bits,0,"");
    return 0;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s