Permutation Algo

Status
Not open for further replies.

BJ@008

Active Member
242
2011
58
0
I tried but still I can't find any easy to understand way to do permutation in c/c++ can anybody please help with.It is urgent.

Actually I am looking for algo which display all permutation of a no like for "123" it should display all permutation i.e.

123
132
213
231
312
321
 
Last edited:
11 comments
permutation like nPr????

---------- Post added at 08:07 PM ---------- Previous post was at 08:00 PM ----------

PHP:
#include <stdio.h>

/* needed prototype definations of the function */

long int premutation(int n, int r);
long int factorial(int num);

void main()
{
    printf("%d", premutation(5, 3));

    getch();
}

/* calculating premutaion */
long int premutation(int n, int r)
{
    return (factorial(n) / factorial(n - r));
}

/* calculatingfactorial */
long int factorial(num)
{
    if (num == 0) return 1;

    return (num * factorial(num -1));
}

may be this helps!
 
Sorry for not being clear.Actually I am looking for algo which display all permutation of a no like for "123" it should display all permutation i.e.

123
132
213
231
312
321
 
@ecoder, in the last line, why did you multiple num by num-1 factorial? can't we simply find factorial of num?
Also, put a condition that if num<0 then factorial = not defined.
 
@Nitish that is recursion as we can find factorial of n as n!=n*n(-1)!.Hence factorial is called as num*factorial(num-1) .

Yes we can simply do it with for loop but recursion is more efficient.
 
give me 5 mins!

---------- Post added at 11:14 PM ---------- Previous post was at 11:07 PM ----------

PHP:
#include <stdio.h>
#include <string.h>

void permutate(char s[],int begin,int end);
void main()
{
    char s[100];
    printf("Enter the string\n");
    gets(s);
    permutate(s,0,strlen(s)-1);
}

void permutate(char s[],int begin,int end)
{
    char t;
    int k;
    if(begin==end)
    {
        printf("%s\n",s);
        return;
    }
    for(k=begin;k<=end;k++)
    {
        t=s[begin],s[begin]=s[k],s[k]=t;
        permutate(s,begin+1,end);
        t=s[begin],s[begin]=s[k],s[k]=t;
    }
}
 
@ecoder, in the last line, why did you multiple num by num-1 factorial? can't we simply find factorial of num?
Also, put a condition that if num<0 then factorial = not defined.


ofc we cant both will yield same output! and as far negative num as considered a programmer would check for negative before passing the value to the function!

---------- Post added at 11:18 PM ---------- Previous post was at 11:17 PM ----------

you mean n!= n*(n-1)! ? weird..


its not weird n! = n(n-1)(n-1)...(1)

so a fair recursive call!
 
well its a simple for loop! i had notepad and pen with me cant draw image in here!

but will try!

---------- Post added at 07:42 PM ---------- Previous post was at 07:41 PM ----------

e0e8fc3bea.gif



may be this helps, its coded on that basis!
 
Status
Not open for further replies.
Back
Top