yeasir007

Showing posts with label permutation. Show all posts
Showing posts with label permutation. Show all posts

Friday, February 02, 2018

Permutation and Combination

Permutation and Combination
Permutation combination re-arranges members of a set and selects a subset. Go to MATH IS FUN to learn details about permutation and combinations.

Here is the implementation of permutation and combination by using recursion function and without using STL.

Permutation:

Here we have used a inputArray having value 5,3,4,2,1. We can replace this input according to our program need.

#include<iostream>
#include<stdio.h>

using namespace std;

int input[5]= {5,3,4,2,1};
int output[25],visited[5];

void permutation(int level,int takenElement,int totalArrayElement);
void printPermutaion(int takenElement);

int main()
{
    for(int t=0;t<5;t++)
    {
        permutation(0,t,5);
    }
    return 0;
}

void permutation(int level,int takenElement,int totalArrayElement)
{
    if(level == takenElement)
    {
        printPermutaion(takenElement);
        return;
    }

    for(int i=0;i<totalArrayElement;i++)
    {
        if(!visited[i])
        {
            visited[i] = true;
            output[level] = input[i];
            permutation(level+1,takenElement,totalArrayElement);
            visited[i] = false;
        }
    }
}

void printPermutaion(int takenElement)
{
    for(int i=0;i<takenElement;i++)
    {
        cout << output[i] << " " ;
    }

    cout << endl;
}