Question

Create the following function in java:

ALGORITHM PERMUTATION GENERATOR PermGenerator(integer n 22) li generates in lexicographical order all permutations llof the i

0 0
Add a comment Improve this question Transcribed image text
Answer #1

SampleOutput:

RawCode:

import java.util.*;
class permutation
{
   public static int fact(int n)        //factorial function in recursion
   {
  
   return(n==1||n==0)?1:n*fact(n - 1);
   }
   public static int PermGenerator(int n)  
   {
     
       int i,j;   //declaring variables
       int k;
       int[] d;   //initialinzing array
       d=new int [n+1];   //allocating memory for array
       for(k=1;k<=n;k++)   //creatinh smallest permutation
           d[k-1]=k;
       for(i=0;i<n;i++)
           System.out.print(d[i]);
       System.out.println("\n");
       for(k=2;k<=fact(n);k++)
       {
           i=n-1;
           j=n;
           while(d[i-1]>d[j-1])
           {
               i=i-1;
               j=j-1;
           }
           j=n;
           while(d[i-1]>d[j-1])
               j=j-1;
           int temp=d[i-1];   //swaping
           d[i-1]=d[j-1];
           d[j-1]=temp;
           i=i+1;       //incrementing i value
           j=n;  
           while(i<j)
           {
               int t=d[i-1];       //swaping
               d[i-1]=d[j-1];
               d[j-1]=t;
               i=i+1;
               j=j-1;
           }
           for(int a=0;a<n;a++)
               System.out.print(d[a]);   //printing permutation
           System.out.println("\n");
       }
       return -1;
}
public static void main(String args[])       //main method
{
    Scanner sc=new Scanner(System.in);      
    int n;
    System.out.println("Enter the n value: ");   //getting input from user
    n=sc.nextInt();
    System.out.println("\n");
    PermGenerator(n);       //calling the PermGenerator() function
}
}

--------------------------------------------------------------------------

Hope you understand.If you have any doubts comment me.Upvote me.

Add a comment
Know the answer?
Add Answer to:
Create the following function in java: ALGORITHM PERMUTATION GENERATOR PermGenerator(integer n 22) li generates in lexicographical...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT