Thursday, July 12, 2012

Miscellaneous – II - Permutation


Permutation : The idea of permuting ‘n’ number of objects is basic. For example, when n = 3 and the objects are a,b, and c, the permutations are abc, acb, bca, bac, cba, and cab. Here there are 6 permutations, or 3 · 2 · 1 = 3! of them. The product “3!” is read as “three factorial” and represents the product of all the positive integers between 1 and 3.



//Permutation of Numbers

#include <stdio.h>
#include <conio.h>

int L=-1,n,num[50],term[50];
  void visited(int k)
      {
           int i;
           num[k]=++L;
           if(L==n)
              {
                   printf("\n\t\t\t");
                   for(i=0;i<n;i++)
                        {
                            printf("%d",term[num[i]]);
                        }
              }
           for(i=0;i<n;i++)
              {
                   if(num[i]==0)
                        {
                            visited(i);
                        }
              }
           L--;
           num[k]=0;
      }

  void main()
      {
           int i=0,j=0;
           clrscr();
           printf("\n\tEnter the Size ");
           scanf("%d",&n);
           printf("\n\tEnte %d Nos.\n",n);
           for(i=0;i<n;i++)
              {
                   num[i]=0;
                   printf("\t\t");
                   scanf("%d",&term[i+1]);
              }
           printf("\n\t\tCombination of : ");
           for(i=1;i<=n;i++)
              {
                   printf("%d",term[i]);
              }
           printf(" is = \n\n ");
           visited(0);
           getch();
      }



Permutation of Characters



#include <stdio.h>
#include <conio.h>

  void swap(char Vch[], int f, int s)
      {
           char ch = Vch[s];
           Vch[s] = Vch[f];
           Vch[f] = ch;
      }

  void perm(char Vch[], int start, int end)
      {
           int i;
           int range = end - start;
           if (range == 1)
              {
                   printf("\t\t%s\n",Vch);
              }
           else
              {
                   for(i=0; i<range; i++)
                     {
                            swap(Vch, start, start+i);
                            perm(Vch, start+1, end);
                            swap(Vch, start, start+i);
                     }
              }
      }

  void main()
      {
           int n,L;
           char Str[50];
           clrscr();
           printf("\n\t\tEnter A String : ");
           gets(Str);
           L=strlen(Str);
           perm(Str, 0, L);
           getch();
      }




No comments: